0

我可以有一个基类,其成员是派生类的实例吗?我应该如何前向声明或包含派生类定义?还是我应该这样做的另一种方式?

// 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&);
};
4

1 回答 1

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();
}
于 2013-09-16T04:08:14.817 回答