在C ++中,为什么地址在指针转换时改变? [英] In C++, why is the address changed when the pointer is converted?
问题描述
以下是代码:
#include< iostream>
using namespace std;
class B1 {
public:
virtual void f1(){
cout< B1\\\
;
}
};
class B2 {
public:
virtual void f1(){
cout< B2\\\
;
}
};
class D:public B1,public B2 {
public:
void f1(){
cout< OK\\\
;
}
};
int main(){
D dd;
B1 * b1d =& dd;
B2 * b2d =& dd;
D * ddd =& dd;
cout<< b1d<< endl;
cout<< b2d<< endl;
cout<< ddd<< endl;
b1d - > f1();
b2d - > f1();
ddd - > f1();
}
输出为:
0x79ffdf842ee0
0x79ffdf842ee8
0x79ffdf842ee0
OK
OK
OK
这看起来让我很困惑,因为我期望 b1d
和 b2d
将与它们都指向
dd
相同。但是,根据结果, b1d
和 b2d
的值不同。我认为这可能与类型铸造有关,但我不知道它是如何工作的。
有没有人有这个想法?
B1
和 B2
。 由于 B1
$ c> B1 首先构造对象的一部分,然后创建对象的 B2
部分,然后创建 D
。
因此,当您将派生类型的指针转换为基本类型时,您所看到的是这些部分在内存中的区别。
b1d
和 ddd
具有相同的地址,因为它们都指向 c>
D
的一部分。 Following is the code:
#include <iostream>
using namespace std;
class B1 {
public:
virtual void f1() {
cout << "B1\n";
}
};
class B2 {
public:
virtual void f1() {
cout << "B2\n";
}
};
class D : public B1, public B2 {
public:
void f1() {
cout << "OK\n" ;
}
};
int main () {
D dd;
B1 *b1d = ⅆ
B2 *b2d = ⅆ
D *ddd = ⅆ
cout << b1d << endl;
cout << b2d << endl;
cout << ddd << endl;
b1d -> f1();
b2d -> f1();
ddd -> f1();
}
The output is :
0x79ffdf842ee0
0x79ffdf842ee8
0x79ffdf842ee0
OK
OK
OK
This looks confusing to me, because I expected b1d
and b2d
would be the same as both of them point to dd
. However, the value of b1d
and b2d
is different according to the result. I thought it may be related to type casting but I'm not sure how it works.
Does anyone have ideas about this?
D
inherits from B1
andB2
.
Since B1
is inherited from first the B1
part of the object is going to be constructed first and then the B2
part of the object will be created then D
.
So what you are seeing is the difference of where those parts are in memory when you cast a pointer of the derived type to the base type.
b1d
and ddd
have the same address as they both point to the beginning of the class in memory.
b2d
is offset as it points to the start of the B2
part of D
.
这篇关于在C ++中,为什么地址在指针转换时改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!