为何无法在派生类构造函数中设置基类私有成员变量?
问题:派生类构造函数中无法赋值基类私有成员的错误
我定义了基类Product,包含私有成员变量price及带参数的构造函数;另有公有继承自Product的派生类PerishableProduct,包含Date类型成员expirationDate及对应构造函数。在PerishableProduct的构造函数中,尝试通过this->price = price赋值时,编译提示'float Product::price'是私有成员的错误,请问问题出在哪里?
代码示例
// 基类Product class Product { float price; public: Product(float price); }; // 派生类PerishableProduct class PerishableProduct : public Product { Date expirationDate; public: PerishableProduct(float price, const Date& expirationDate); }; // 派生类构造函数实现 PerishableProduct::PerishableProduct(float price, const Date& expirationDate) : Product(float()) { this->expirationDate = expirationDate; this->price = price; }
编译报错信息
note: declared private here
float price;
error: ‘float Product::price’ is private within this context
this->price = price;
原因及解决方案
错误原因
- C中,基类的私有成员只能被基类自身的成员函数访问,哪怕是公有继承的派生类,也没有直接访问基类私有成员的权限。你在
PerishableProduct构造函数里直接通过this->price访问基类私有成员price,违反了C的访问权限规则。 - 派生类构造函数初始化列表中调用
Product(float())只是创建了一个临时float对象来初始化基类,并没有正确传递需要的price值。
修正方案
在派生类构造函数的初始化列表中,直接调用基类的带参数构造函数传递price,同时可以一并初始化expirationDate,避免后续赋值操作:
PerishableProduct::PerishableProduct(float price, const Date& expirationDate) : Product(price), expirationDate(expirationDate) {}
补充说明
如果后续需要在派生类中读取或修改price,可以在基类中提供公有的接口函数,比如:
class Product { float price; public: Product(float price) : price(price) {} // 获取price的getter float getPrice() const { return price; } // 修改price的setter(按需添加) void setPrice(float newPrice) { price = newPrice; } };
之后派生类就可以通过这些接口间接访问基类的私有成员。
内容的提问来源于stack exchange,提问作者Proxie
相关产品推荐
相关产品推荐

