如何实例化一个派生类对象,其基类构造函数是私有(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
如何修改代码以消除编译错误?
最佳答案
有两种方式:
- 将基类构造函数设为
public
或protected
。 - 或者,使派生类成为基类的
friend
。见demo
关于c++ - 实例化一个派生类对象,其基类ctor是私有(private)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9851586/