我可以有一个基类,其成员是派生类的实例吗?我应该如何前向声明或包含派生类定义?还是我应该这样做的另一种方式?
// 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&);
};