我目前正忙于继承,我正在处理名为 Vehicle
的基类和名为 Truck
的子类。子类继承自基类。我正在管理 Vehicle
的公共(public)成员的继承,但无法在函数 void describe() const
中访问名为 top_speed
的私有(private)成员>.
我知道可以在代码(下面提供)中执行此操作以从基类访问,但似乎我遗漏了一些东西。在代码的评论部分,我的问题为您更清楚地说明了。
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;
};
在 Truck 类中是这样的:
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
函数中做些什么来修复它?
最佳答案
最干净的方法是在基类中有一个公共(public)访问函数,返回当前值的拷贝。 最后您要做的是将私有(private)数据公开给子类 (*)。
double Vehicle::getTopSpeed( void ) const {
return this->top_speed;
}
然后像这样在 Truck 类中使用它:
void Truck::describe( void ) const {
cout << "This truck's top speed is " << this->getTopSpeed() << endl;
}
(是的,我知道,“this->”是多余的,但它用于说明它正在访问类的成员/方法)
(*) 因为,真的,如果您要公开父类(super class)的数据成员,那么您为什么要使用私有(private)/ protected /公共(public)?
关于c++ - 如何从继承的子类访问基类中的私有(private)成员 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25016470/