在派生类中重写成员字段 [英] Override member field in derived classes

查看:62
本文介绍了在派生类中重写成员字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一个代码段:

#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 计算机。我盒子上的输出为

Run the compiled executable and I find the result is out of my expectation on my llvm-g++ 4.2 machine. The output on my box is as

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

我想在做什么该代码将覆盖 Derived 类中的成员字段( b )。
因为我认为 Base Derived 都需要访问此字段,所以我定义了 Base 中获取成员函数,因此 Derived 可以继承它。
然后我尝试从不同的对象中获取成员字段。

What I want to do in the code is to override a member field (b) in Derived class. Since I think both Base and Derived need to access this field, I define a get member function in Base, thus Derived can inherit it. Then I try to get the member field from different objects.

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

The result shows that I still get original b in Base by d.get() instead of that in Derived, which is what I expected the code to do. Anything wrong with the code (or my understanding)? Is this behavior specified in the specification? What is the right way to override a member field and properly define its getter and setter?

推荐答案

新的 b 不会覆盖基数的 b

The new b added in the derived class doesn't override base's b. It just hides it.

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

So, in the derived class you have two b and the virtual method prints corresponding b.

这篇关于在派生类中重写成员字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆