Programing

실제로 C ++에서 Private 또는 Protected 상속이 필요한 이유는 무엇입니까?

lottogame 2020. 12. 12. 09:56
반응형

실제로 C ++에서 Private 또는 Protected 상속이 필요한 이유는 무엇입니까?


C ++에서는 기본 클래스에서 private / protected를 상속하고 싶은 경우를 생각할 수 없습니다.

class Base;
class Derived1 : private Base;
class Derived2 : protected Base;

정말 유용합니까?


기본 클래스의 일부 멤버에 액세스하려는 경우 유용하지만 클래스 인터페이스에 노출되지는 않습니다. 개인 상속은 일종의 구성으로도 볼 수 있습니다. C ++ faq-lite 는이 문장을 설명하기 위해 다음 예제를 제공합니다.

class Engine {
 public:
   Engine(int numCylinders);
   void start();                 // Starts this Engine
};

class Car {
  public:
    Car() : e_(8) { }             // Initializes this Car with 8 cylinders
    void start() { e_.start(); }  // Start this Car by starting its Engine
  private:
    Engine e_;                    // Car has-a Engine
};

동일한 의미를 얻기 위해 다음과 같이 car Class를 작성할 수도 있습니다.

class Car : private Engine {    // Car has-a Engine
 public:
   Car() : Engine(8) { }         // Initializes this Car with 8 cylinders
   using Engine::start;          // Start this Car by starting its Engine
}; 

그러나 이러한 방법에는 몇 가지 단점이 있습니다.

  • 당신의 의도는 훨씬 덜 명확합니다
  • 악의적 인 다중 상속으로 이어질 수 있습니다.
  • 보호 된 멤버에 액세스 할 수 있으므로 Engine 클래스의 캡슐화를 중단합니다.
  • 목표가 단순한 구성 인 경우 원하지 않는 엔진 가상 메서드를 재정의 할 수 있습니다.

Private은 몇 가지 상황에서 유용 할 수 있습니다. 그중 하나는 정책입니다.

부분 클래스 템플릿 전문화가이 디자인 문제에 대한 답입니까? .

유용한 또 다른 경우는 복사 및 할당을 금지하는 것입니다.

struct noncopyable {
    private:
    noncopyable(noncopyable const&);
    noncopyable & operator=(noncopyable const&);
};

class my_noncopyable_type : noncopyable {
    // ...
};

사용자가 noncopyable*객체에 대한 유형의 포인터를 가지기를 원하지 않기 때문에 비공개 적으로 파생됩니다. 그것은 복사 불가능한 것뿐만 아니라 다른 많은 클래스도 중요합니다 (가장 일반적인 정 책임).


공개 상속 모델 IS-A.
비공개 상속 모델은 조건에 따라 구현됩니다.
IS-IMPLEMENTED-IN-TERMS-OF와 동등한 격리 모델 HAS-A.

Sutter on the topic. He explains when you'd choose non-public inheritance over containment for implementation details.


For instance, when you want to reuse the implementation, but not the interface of a class AND override its virtual functions.


Private inheritance is mostly used for wrong reason. People use it to IS-IMPLEMENTED-IN-TERMS-OF, as indicated in an earlier answer, but in my experience it's always more clean to keep a copy rather than inherit from class. Another earlier answer, the one about CBigArray, provides a perfect example of this anti-pattern.

I realize that there may be cases when has-a does not work due to over-zealous use of "protected", but it's better to fix the broken class than to break a new class.


I've used both private and protected inheritence at one point or other.

Private inheritence is useful when you want something to have the behaviour of the base class, and then be able to override that functionality, but you don't want the whole world to be aware of it and use it. You can still use the interface of a privately derived class by having a function return that interface. It's also useful when you can have things register themselves to listen for callbacks as they can register themselves using the private interface.

Protected inheritence is especially useful when you have a base class that derives useful functionality from another class but you only want its derived classes to be able to use it.


I once implemented these data structures as classes:

  • Linked list
  • Generic array (abstract)
  • Simple array (inherits from generic array)
  • Big array (inherits from generic array)

The big array's interface would make it look like an array, however, it was actually a linked list of fixed-size simple arrays. So I declared it like this:

template <typename T>
class CBigArray : public IArray, private CLnkList {
    // ...

참고URL : https://stackoverflow.com/questions/374399/why-do-we-actually-need-private-or-protected-inheritance-in-c

반응형