继承实际上会导致类的成员被“继承”吗?

时间:2012-03-17 14:47:58

标签: 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 的副本,这应该导致{ {1}}打印值ab->x

我在这里缺少什么?我发现很难理解为什么这会打印10尽管继承。

5 个答案:

答案 0 :(得分:4)

这是一个简单的图,简要说明了成员变量的继承:

enter image description here

创建ChildClass时,BaseClass已创建并存在于ChildClass中。可以从ab访问变量cChildClassBaseclass(取决于访问修饰符,例如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)

Bx继承A(在A的构造函数中设置值为10),然后立即在其自己的构造函数中将其设置为0。 / p>

xA只分享了一个B

答案 4 :(得分:0)

或者换句话说,成员x没有隐含的0-ness或10-ness。会发生什么,因为您通过B调用调用new的构造函数。 x是在A中还是在B中定义,还是作为全局变量,无关紧要。 B的构造函数将其设置为0,因此它为0.

这有帮助吗?

相关问题