实例化派生类对象,其基类ctor是私有的

nit*_*ian 13 c++ inheritance compiler-errors private-constructor

如何实例化一个派生类对象,其基类ctor是私有的?

由于派生类ctor隐式调用基类ctor(私有),编译器会给出错误.

请考虑以下示例代码:

#include <iostream>

using namespace std;

class base
{
   private:
      base()
      {
         cout << "base: ctor()\n";
      }
};

class derived: public base
{
   public:
      derived()
      {
         cout << "derived: ctor()\n";
      }
};

int main()
{
   derived d;
}
Run Code Online (Sandbox Code Playgroud)

此代码给出了编译错误:

access_private_ctor_in_base_class.cpp:在构造函数 derived::derived()': accessing_private_ctor_in_base_class.cpp:9: error:base :: base()'是私有的access_private_ctor_in_base_class.cpp:18:错误:在此上下文中

如何修改代码以删除编译错误?

Naw*_*waz 17

有两种方法:

  • 使基类构造函数publicprotected.
  • 或者,使派生类成为friend基类.看看演示