【发布时间】:2013-08-18 20:04:04
【问题描述】:
一个简短的例子输出了一个奇怪的结果!
#include <iostream>
using namespace std;
struct A { int a; };
struct B { int b; };
struct C : A, B
{
int c;
};
int main()
{
C* c = new C;
B* b = c;
cout << "The address of b is 0x" << hex << b << endl;
cout << "The address of c is 0x" << hex << c << endl;
if (b == c)
{
cout << "b is equal to c" << endl;
}
else
{
cout << "b is not equal to c" << endl;
}
}
让我很吃惊的是输出应该如下:
The address of b is 0x003E9A9C
The address of c is 0x003E9A98
b is equal to c
让我好奇的是:
0x003E9A9C不等于0x003E9A98,但是输出是“b等于c”
【问题讨论】:
-
我看不出这个问题与 C(语言)有什么关系。标题和标签似乎与问题的正文不一致。
-
我修正了标题,如果您不同意,请查看并回滚。
-
@xmllmx 你应该使用
cout << "The address of c is 0x" << hex << static_cast<B*>(c) << endl;,因为这就是b==c对右侧的作用。 -
@PeterT 这就是整个问题的意义所在,并且显然令 OP 感到惊讶:为什么原始地址不同,而直接比较则不然。演员只会隐藏令人惊讶的差异,而不是解释它;-)
-
我想打四个投票结束的推特。平等的概念(它的含义以及可以存在多少种)是数学和计算的核心。
标签: c++ pointers multiple-inheritance