【问题标题】:Derived class calls an inherited function that uses non-inherited members派生类调用使用非继承成员的继承函数
【发布时间】:2019-10-27 19:58:54
【问题描述】:

我有一个基类,它有两个私有变量和一个打印它们的公共方法。通过从它继承,我得到了一个使用未继承到派生类的变量的方法。但是,它可以工作并使用基类构造函数给出的值调用该方法。

甚至通过添加到派生他自己的默认构造函数,和相同的int x, y;变量,具有不同的默认值,该方法打印基类默认值。为什么会发生这种情况,我该如何避免?我知道受保护的成员,但这里仍然发生了什么?我首先尝试使用空派生类(没有构造函数和变量),结果是一样的。它怎么能使用不被继承的变量呢?

class base {
private:
    int x, y;

public:
    base(int px=1, int py=2)
        :x(px), y(py)
    {}

    inline void print() const {
        cout << x << ", " << y << '\n';
    }
};

class derived : public base {
private:
    int x, y;
public:
    derived(int px = 3, int py = 3)
        :x(px), y(py)
    {}
};

int main{
        derived e;
        e.print(); // prints 1, 2
}

【问题讨论】:

    标签: c++ inheritance encapsulation


    【解决方案1】:

    base::print 看不到derived 中的成员变量。您有几个选择:

    1. 如果您确实希望 base::xderived::x 有所不同,请使用 protected
    2. pxpy 传递给base 的构造函数:derived(int px = 3, int py = 3) : base(px, py) { }
    3. base::print 设为virtual 成员函数并在derived 中覆盖它。

    哪个选项最好取决于您的要求。

    【讨论】:

    • 我只是将 base::print 复制到了derived 中,而没有将其变为虚拟并且它起作用了...
    • @Denomycor - 如果有人有指向base 的指针或引用并调用print,你会遇到麻烦。你真的很想成功virtual
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2017-10-17
    相关资源
    最近更新 更多