[英]Instantiate a derived class object, whose base class ctor is private
How to instantiate a derived class object, whose base class ctor is private? 如何实例化一个派生类对象,其基类ctor是私有的?
Since the derived class ctor implicitly invokes the base class ctor(which is private), the compiler gives error. 由于派生类ctor隐式调用基类ctor(私有),编译器会给出错误。
Consider this example code below: 请考虑以下示例代码:
#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;
}
This code gives the compilation error: 此代码给出了编译错误:
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 contextaccess_private_ctor_in_base_class.cpp:在构造函数
derived::derived()': accessing_private_ctor_in_base_class.cpp:9: error:
base :: base()'是private acces_private_ctor_in_base_class.cpp:18:错误:在此上下文中
How can i modify the code to remove the compilation error? 如何修改代码以删除编译错误?
You can't inherit from a base-class whose only constructor is private. 您不能从只有构造函数是私有的基类继承。 1
1
So make the base-class constructor public/protected, or add another base-class constructor. 因此,将基类构造函数设置为public / protected,或者添加另一个基类构造函数。
You can't. 你不能。 That's usually the reason to make the only c'tor private, disallow inheritance.
这通常是使唯一的c'tor私有,不允许继承的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.