如何實例化派生類對象,其基類ctor是私有的?實例化派生類對象,其基類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;
}
此代碼給編譯錯誤:
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
我如何修改代碼以刪除編譯錯誤?
@ Nawaz:讓派生類成爲基類的朋友! – 2012-03-24 12:18:23