如何通过继承从子类访问基类中的私有成员(C++)

Joe*_*e_B 3 c++ inheritance private class members

我目前正忙于继承,并且正在使用一个名为 的基类Vehicle和一个名为 的子类Truck。子类继承自基类。我正在管理 的公共成员的继承Vehicle,但无法访问top_speed函数中调用的私有成员void describe() const

我知道可以在代码(下面提供)中执行此操作以从基类访问,但似乎我遗漏了一些东西。在代码的评论部分中,我的问题为您更清楚地说明了。

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;
}
Run Code Online (Sandbox Code Playgroud)

在我的Vehicle班级中,它在哪里:

class Vehicle
{
private:
    double top_speed;

public:
    //other public members
    void describe() const;
};
Run Code Online (Sandbox Code Playgroud)

在 Truck 类中是这样的:

class Truck: public Vehicle
{
private:
    double load_capacity;
public:
    //other public members
    void describe() const;  
};
Run Code Online (Sandbox Code Playgroud)

更清楚地说,我收到此错误:

error: 'double Vehicle::top_speed' is private
Run Code Online (Sandbox Code Playgroud)

我可以在函数中做什么void Truck::describe() const来修复它?

haa*_*vee 5

最干净的方法是在基类中使用公共访问器函数,返回当前值的副本。您要做的最后一件事是将私有数据暴露给子类(*)。

double Vehicle::getTopSpeed( void ) const {
    return this->top_speed;
}
Run Code Online (Sandbox Code Playgroud)

然后在 Truck 类中使用它,如下所示:

void Truck::describe( void ) const {
   cout << "This truck's top speed is " << this->getTopSpeed() << endl;
}
Run Code Online (Sandbox Code Playgroud)

(是的,我知道,“this->”是多余的,但它用于说明它正在访问类的成员/方法)

(*) 因为,实际上,如果您要公开超类的数据成员,那么为什么要使用私有/受保护/公共呢?

  • @LuchianGrigore,当它不与公共设置器配对时,它当然具有更多优点。 (2认同)