问题描述
例如,在这段代码中,如果 line [a]
被注释掉,则输出为0.
For example, in this piece of code, if line [a]
is commented out, the output is 0.
#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;
}
$ g++ inh2.cpp
$ ./a.out
10
$
我有两个问题:
- 在上述情况下,
ab-> gt; x
如何解析为10
对象是类B
,因此应该0
。 - 为什么注释
Line [a]
更改代码的行为?我的推理是,x
将继承,这应该导致相同的行为。
- How does
ab->x
resolve to10
in the above case? The object is of typeclass B
, and thus should value to0
. - Why does commenting
Line [a]
change the behaviour of the code? My reasoning is thatx
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 ofclass 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.
我在哪里错了?
推荐答案
-
是的,它是
B
类型,但是你将它指定为A
,因此它使用在A上定义的x
(当我们处理一个指向A的指针时,我们不知道<$ c
Yes, it is of type
B
, but you are assigning it as a pointer to anA
, and therefore it is using thex
defined on A (as when we're dealing with a pointer to A, we don't know thatB
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, A
s constructor is called first, then B
s constructor, which sets x
(in its base class) to 0. There is only one x
at this point, and Bs constructor is called last.
这篇关于继承:为什么在继承和提供的变量之间的行为有差别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!