覆盖派生类中的成员字段

夏季_更多_更多_茶

我下面有一个代码片段:

#include <iostream>

using namespace std;

class Base {
public:
    Base() : b(0) {}
    int get();
    virtual void sayhello() { cout << "Hello from Base with b: " << b << endl; }
private:
    int b;
};

int Base::get() {sayhello(); return b;} 

class Derived : public Base {
public:
    Derived(double b_):b(b_){}
    void sayhello() { cout << "Hello from Derived with b: " << b << endl; }
private:
    double b;
};

int main() {
    Derived d(10.0);
    Base b = d;

    cout << "Derived b: " << d.get() << endl;
    cout << "Base b: " << b.get() << endl;
}

运行编译的可执行文件,我发现结果在我的llvm-g ++ 4.2计算机上超出了我的预期我的盒子上的输出是

Hello from Derived with b: 10
Derived b: 0
Hello from Base with b: 0
Base b: 0

我要在代码中执行的操作是覆盖类中的成员字段(bDerived因为我认为无论是BaseDerived需要访问这个领域,我定义了一个get在成员函数Base,因此Derived可以继承它。然后,我尝试从不同的对象获取成员字段。

结果表明,我仍然是原始bBasebyd.get()而不是in Derived,这是我期望代码执行的操作。代码有什么问题(或我的理解)?规范中是否指定了此行为?重写成员字段并正确定义其getter和setter的正确方法是什么?

马苏德

b在派生类中添加的新内容不会覆盖base的b它只是隐藏

因此,在派生类中,您有两个b,并且虚方法打印相应的b

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章