java 怎么新建一个派生类_C:如何强制派生类来设置基本成员变量?

我有一个带有成员变量的基类(最好是 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 中声明的几个方法实现自己的行为 .

任何指针都表示赞赏 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值