【发布时间】:2013-10-08 23:12:29
【问题描述】:
我有一个带有成员变量的基类(最好是private),我需要强制派生类使用基于其实现的值对其进行初始化;很像纯虚函数。
为了澄清,我想在 Base 中声明一个成员,让派生类对其进行初始化,如果不这样做,则会出现编译器错误。在下面的代码中,我将Base 的默认构造函数声明为protected。然后将Derived的默认构造函数声明为private。
class Base {
private:
int _size;
protected:
Base(){}
/* pure virtual methods */
public:
Base(int size) : _size(size){} // must enforce derived to call this.
virtual ~Base(){}
/* more pure virtual methods */
};
class Derived : public Base {
private:
Derived() {}
public:
Derived(int size) : Base(size) {
//Base::Base(size);
}
};
int main()
{
Derived* d1 = new Derived(); // throws an error as needed:
// "Cannot access private member declared in class 'Derived'"
Derived* d2 = new Derived; // throws an error as needed:
// "Cannot access private member declared in class 'Derived'"
Derived* d3 = new Derived(5); // works as needed
return 0;
}
上面代码的问题是,如果Derived的另一个定义没有隐藏默认构造函数。我仍然遇到未初始化的Base::_size。
我不知道除了继承之外是否还有其他方法可以解决这个问题,因为我仍然需要派生类来为Base 中声明的几个方法实现它们自己的行为。
任何指针表示赞赏。
【问题讨论】:
-
Base::Base(size);这可能不是你认为的那样。如果要调用基类ctor,请使用mem-initializer-list:Derived(int size) : Base(size) { /*...*/ } -
好的,谢谢。刚刚编辑了代码。
-
拥有带参数的构造函数会自动移除默认构造函数。你不需要做一个私人的。
-
@NeilKirk 是的,但它不强制用户使用参数化 ctor。如果类没有显式定义默认构造函数,则编译器会自动创建它。对吗?
-
@mbadawi23 如果存在用户声明的 ctor,则将不隐式声明默认 ctor。
标签: c++ inheritance