【问题标题】:Cpp inheritance - Parent function, child variableCpp继承-父函数,子变量
【发布时间】:2021-08-24 21:11:40
【问题描述】:

我有一个带有函数和子类的类。
在以下代码中,我想以 d.getX() 返回 40 的方式覆盖 int x

using std::cout, std::endl;

class Base {
protected:
    int x;
    int y;
public:
    Base(int y) : y(y) {};
    int getX() {
        return x;
    }
};

class Derived : public Base {
protected:
    int x = 40;
public:
    using Base::Base;
};

int main() {
    Base d(10);
    cout << d.getX() << endl; // want to print 40
    return 0;
}

这可能吗?谢谢!

【问题讨论】:

  • 这个问题表明对继承的工作原理缺乏了解。我建议看看我们的list of textbooks

标签: c++ inheritance overriding


【解决方案1】:

好吧,对于初学者来说,您并没有创建Derived 对象,因此您将x 的值设置为40 的代码永远不会被调用。它甚至可能会被完全优化。

但即便如此,Derived 还是声明了自己的x 成员,它遮蔽Base 中的x 成员,因此Base::x 永远不会被赋值。您需要摆脱 Derived::x 并改为使 Derived 更新 Base::x

试试这个:

#include <iostream>
using std::cout;
using std::endl;

class Base {
protected:
    int x;
    int y;
public:
    Base(int y) : y(y) {};
    int getX() {
        return x;
    }
};

class Derived : public Base {
public:
    Derived(int y) : Base(y) { x = 40; }  
};

int main() {
    Derived d(10);
    cout << d.getX() << endl;
    return 0;
}

Online Demo

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多