来自 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
尽管有继承。
最佳答案
这里用一个简单的图从成员变量的角度来简单解释一下继承:
当 ChildClass
创建时,BaseClass
也被创建并存在于 ChildClass 中。变量 a
、b
和 c
可以从 ChildClass
和 Baseclass
访问(取决于访问修饰符,例如 public、private 和 protected)。 它们是共享的,而不是复制的。
关于c++ - 继承实际上会导致类的成员为 'inherited' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750895/