c++ - 基类可以有一个成员是派生类的实例吗?

标签 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&);
};

最佳答案

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

#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();
}

关于c++ - 基类可以有一个成员是派生类的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820182/

相关文章:

c++ - 对 Cocos2d-x 大小类型的引用不明确

c++ - AIX 5.3 上的 mlockall

c++ - 使用 XFRM 消息更新 IPsec key

c++ - 在派生类的构造函数中初始化父类(super class)

java - Main 不会从相应的类中提取信息。继续产生错误

c++ - 从 C++ 文件中读取不同类型的数字数据

c++ - 使用 Media Foundation 进行无缝视频播放

c++ - 关于 C++ 编程语言的问题

c++ - vector::push_back 坚持使用复制构造函数,尽管提供了移动构造函数

c++ - 以不同方式对待子类/避免代码重复