从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
的副本,这应该导致{ {1}}打印值ab->x
。
我在这里缺少什么?我发现很难理解为什么这会打印10
尽管继承。
答案 0 :(得分:4)
这是一个简单的图,简要说明了成员变量的继承:
创建ChildClass
时,BaseClass
已创建并存在于ChildClass中。可以从a
和b
访问变量c
,ChildClass
和Baseclass
(取决于访问修饰符,例如public,private和protected)。 他们是共享的,而不是复制的。
答案 1 :(得分:1)
我希望它继承成员变量x
的副本
不,您不通过复制继承。继承B
的{{1}}会导致A
的每个对象都包含B
类型的子对象。由于A
中定义了x
,因此您可以通过分配到A
来修改A
子对象。
下面的代码重新构造使这个子对象可见:
x
这当然与继承不同,因为类型#include <iostream>
using namespace std;
struct A {
int x;
A() { x = 10; }
};
struct B {
A subobject;
B(): subobject() { this->subobject.x = 0; }
};
int main() {
B* ab = new B;
cout << ab->subobject.x << endl; // prints 0
}
和A
现在不再相关(您无法从B
转换为B
),但它有点类似于编译器在使用继承时所看到的内容。
答案 2 :(得分:1)
inherit a copy of member variable x
- 好吧,它没有继承副本,它只是继承了变量。它确实。
首先A
的构造函数运行(x = 10),B
(x = 0)的构造函数。之后,x
显然是0
。
根据您的评论,我认为您正在寻找组合而不是继承:
class B {
public:
A a;
int x;
};
答案 3 :(得分:0)
B
从x
继承A
(在A
的构造函数中设置值为10),然后立即在其自己的构造函数中将其设置为0。 / p>
x
和A
只分享了一个B
。
答案 4 :(得分:0)
或者换句话说,成员x
没有隐含的0-ness或10-ness。会发生什么,因为您通过B
调用调用new
的构造函数。 x
是在A
中还是在B
中定义,还是作为全局变量,无关紧要。 B
的构造函数将其设置为0,因此它为0.
这有帮助吗?