继承:为什么在继承和提供的变量之间的行为有差别? [英] Inheritance: why is there a difference in behaviour between inherited and supplied variables?

查看:177
本文介绍了继承:为什么在继承和提供的变量之间的行为有差别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在这段代码中,如果 line [a] 被注释掉,则输出为0.

For example, in this piece of code, if line [a] is commented out, the output is 0.


inh2.cpp



#include<iostream>
using namespace std;

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

class B : public A {
    public:
        int x;  // <--------- [a]
        B() { x = 0; }
};

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




结果来自gcc

results from gcc



$ g++ inh2.cpp
$ ./a.out
10
$

我有两个问题:


  1. 在上述情况下, ab-> gt; x 如何解析为 10 对象是类B ,因此应该 0

  2. 为什么注释 Line [a] 更改代码的行为?我的推理是, x 将继承,这应该导致相同的行为。

  1. How does ab->x resolve to 10 in the above case? The object is of type class B, and thus should value to 0.
  2. Why does commenting Line [a] change the behaviour of the code? My reasoning is that x would have anyways been inherited, which should result in same behaviour.






我对上述Q#1的推理:


My reasoning for Q #1 above:


  • ab 指向 B类的对象的内存位置。

  • ab points to the memory location of an object of class B. It is a physical object in the sense that all the variables with their values are assigned memory.

变量 x 在此对象内存储值 0

Variable x within this object stores value 0.

ab- ; x 完成后,ab告诉我们对象的内存位置,我们去查看里面的内容,发现x是0.所以我们应该打印0。

When ab->x is done, ab tells us the memory location of the object, and we go look inside it to find that x is 0. So we should print 0.

我在哪里错了?

推荐答案


  1. 是的,它是 B 类型,但是你将它指定为 A ,因此它使用在A上定义的 x (当我们处理一个指向A的指针时,我们不知道<$ c

  1. Yes, it is of type B, but you are assigning it as a pointer to an A, and therefore it is using the x defined on A (as when we're dealing with a pointer to A, we don't know that B even exists, even though that's what you allocated).

当你注释掉这一行时,在构造过程中阶段, A 的构造函数先调用,然后 B 的构造函数设置 x (在其基类中)为0.此时只有一个 x ,Bs构造函数最后调用。

When you comment out the line, during the construction phase, As constructor is called first, then Bs constructor, which sets x (in its base class) to 0. There is only one x at this point, and Bs constructor is called last.

这篇关于继承:为什么在继承和提供的变量之间的行为有差别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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