基类是否可以具有作为派生类实例的成员?

时间:2013-09-16 03:53:52

标签: c++ inheritance c++11

我可以拥有一个基类,其成员是派生类的实例吗?我应该如何转发声明或包含派生类定义?或者我还有另一种方法可以做到这一点吗?

// base.h

class DerivedClass;  // Is forward declaration sufficient?

class Base {
 public:
  virtual ~Base();
  virtual void DoStuff() = 0;
  void DoSomethingWithD() {
    d_.Foo();
  }
 protected:
  DerivedClass d_;
};

// derived.h

#include "base.h"

class Derived : public Base {
 public:
  Derived();
  void DoStuff();
  void Foo();
 private:
  Derived(const Derived&);
  void operator=(const Derived&);
};

// other_derived.h

#include "base.h"

class OtherDerived : public Base {
 public:
  OtherDerived();
  void DoStuff();
 private:
  OtherDerived(const OtherDerived&);
  void operator=(const OtherDerived&);
};

1 个答案:

答案 0 :(得分:1)

这对您有用,请参阅有关更改的评论:

#include <memory>

class Derived;

class Base {
 public:
  virtual ~Base();
  virtual void DoStuff() = 0;
  void DoSomethingWithD();      // no longer defined in-line
 protected:
  std::unique_ptr<Derived> d_;  // storing as a pointer as Derived is still incomplete
};

class Derived : public Base {
 public:
  Derived();
  void DoStuff();
  void Foo();
 private:
  Derived(const Derived&);
  void operator=(const Derived&);
};

class OtherDerived : public Base {
 public:
  OtherDerived();
  void DoStuff();
 private:
  OtherDerived(const OtherDerived&);
  void operator=(const OtherDerived&);
};

// definition moved down here where Derived is a complete type
void Base::DoSomethingWithD() { 
  d_->Foo();
}