c++ - 实例化一个派生类对象,其基类ctor是私有(private)的

标签 c++ inheritance compiler-errors private-constructor

如何实例化一个派生类对象,其基类构造函数是私有(private)的?

由于派生类ctor隐式调用基类ctor(private),编译器报错。

考虑下面的示例代码:

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

这段代码给出了编译错误:

accessing_private_ctor_in_base_class.cpp: In constructor derived::derived()': accessing_private_ctor_in_base_class.cpp:9: error:base::base()' is private accessing_private_ctor_in_base_class.cpp:18: error: within this context

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

最佳答案

有两种方式:

  • 将基类构造函数设为publicprotected
  • 或者,使派生类成为基类的 friend 。见demo

关于c++ - 实例化一个派生类对象,其基类ctor是私有(private)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9851586/

相关文章:

c++ - 打开文件 'write' 比打开文件 'read' 花费的时间多 10-50 倍

c++ - 类体之外的成员函数定义导致错误

c++ - 单例继承,派生类无法在父类中实例化?

java - 为什么在Java中的文件输入输出代码中出现一些错误?

compiler-errors - typescript : Build: Supplied parameters do not match any signature of call target

c++ - REDHAWK IDE生成的端口类型frontend::OutDigitalScanningTunerPort定义在哪里?

c++ - 在 Linux 上使用 g++ 运行 clang scan-build

inheritance - "overriding":initform setting in defclass for superclass (CLOS)

javascript - 为什么 JavaScript 使用原型(prototype)继承来实现?

error-handling - 为什么标准错误需要在main中装箱,而不是io错误?