我有一个带有成员变量的基类(最好是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
.
任何指针表示赞赏。