【发布时间】:2014-09-20 21:26:45
【问题描述】:
我目前正忙于继承,我正在使用一个名为Vehicle 的基类和一个名为Truck 的子类。子类继承自基类。我正在管理Vehicle 的公共成员的继承,但无法访问函数void describe() const 中名为top_speed 的私有成员。
我知道可以在代码中执行此操作(如下提供)以从基类进行访问,但似乎我遗漏了一些东西。在代码的注释部分中,我的问题更清楚地说明了您。
void Truck::describe() const : Vehicle()
/*I know this is a way-> : Vehicle()
to inherit from the Vehicle class but how
can I inherit the top_speed private member of Vehicle in the
void describe() const function of the Truck class?*/
{
cout << "This is a Truck with top speed of" << top_speed <<
"and load capacity of " << load_capacity << endl;
}
在我的Vehicle 类中它在哪里:
class Vehicle
{
private:
double top_speed;
public:
//other public members
void describe() const;
};
在卡车类中是这样的:
class Truck: public Vehicle
{
private:
double load_capacity;
public:
//other public members
void describe() const;
};
为了更清楚,我收到了这个错误:
error: 'double Vehicle::top_speed' is private
我可以在 void Truck::describe() const 函数中做什么来修复它?
【问题讨论】:
-
void Truck::describe() const : Vehicle()不是有效的语法。无论如何,私有的重点是成员不暴露给派生类。有一个完全独立的访问说明符。 -
简单来说,你不能从一个类访问私有成员到另一个类。
-
如果你想做意大利面,你也可以在
Vehicle课堂上friend class Truck;。 (即不要)。 -
我希望你知道
Truck的describe不会覆盖Vehicle的。
标签: c++ class inheritance private members