我有一个带有成员变量的基类(最好是 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 的另一个定义没有't hide the default constructor. I'仍然停留在未初始化的 Base::_size 上 .
我不知道除了继承之外是否还有其他方法可以解决这个问题,因为我仍然需要派生类来为 Base 中声明的几个方法实现自己的行为 .
任何指针都表示赞赏 .