c++ - 继承实际上会导致类的成员为 'inherited' 吗?

标签 c++ inheritance

来自 an answer on Inheritance: why is there a difference in behaviour between inherited and supplied variables? ,我知道下面的代码打印了 0,因为只有一份 x

#include<iostream>
using namespace std;

class A {
    public:
        int x;
        A() { x = 10; }
};

class B : public A {
    public:
        B() { x = 0; }
};

int main() {
    A* ab = new B;
    cout << ab->x << endl; // prints 0
}

但这不是违背了继承的本意吗?

我编写了 class B 以从 class A 公开访问,我希望它继承成员变量 x 的拷贝,这应该导致 ab->x 打印值 10

我在这里错过了什么?我发现很难理解为什么这会打印 0 尽管有继承。

最佳答案

这里用一个简单的图从成员变量的角度来简单解释一下继承:

enter image description here

ChildClass 创建时,BaseClass 也被创建并存在于 ChildClass 中。变量 abc 可以从 ChildClassBaseclass 访问(取决于访问修饰符,例如 public、private 和 protected)。 它们是共享的,而不是复制的

关于c++ - 继承实际上会导致类的成员为 'inherited' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750895/

相关文章:

c++ - std::forward 和引用折叠的工作

c++ - 如何在不访问 int 到字符串函数的情况下将 int 转换为字符串(在 C++ 中)

c++ - 为什么我的析构函数只被调用一次而不是在 delete(a) 调用中?

c# - 在通用方法中返回接口(interface)继承的类

C++ 代码翻译和名称查找

c++ - 整数类型大小问题

android - JNI : Access to 'keySet' method with android. os.Bundle 实例

c++ - CRTP 和复制/移动赋值/构造函数继承

python - 只导入一个类的静态方法

c# - 在数据类型和调用匹配方法之间进行选择?