【发布时间】:2012-09-12 18:51:44
【问题描述】:
谁能解释以下代码的行为?
- 为什么在第一种情况下我们有
b = 3,即b2 == &d是真的? - 为什么在案例 2 中正常?我打印了
b2和d的地址,它们是不同的。
#include <iostream>
using namespace std;
class A
{
public:
A() : m_i(0) { }
protected:
int m_i;
};
class B
{
public:
B() : m_d(0.0) { }
protected:
double m_d;
};
class C
: public A
, public B
{
public:
C() : m_c('a') { }
private:
char m_c;
};
int main()
{
C d;
B *b2 = &d;
cout << &d << endl;
cout << b2 << endl;
const int b = (b2 == &d) ? 3 : 4; ///Case1: b = 3;
const int c = (reinterpret_cast<char*>(b2) == reinterpret_cast<char*>(&d)) ? 3 : 4; //Case 2: c = 4;
std::cout << b << c << std::endl;
return 0;
}
【问题讨论】:
-
+1 ,因为这是一个很好的例子,很好地说明了多继承对指针的影响
-
+1 同样。很好的例子,尤其是没有虚拟的,可以真正让人们通过铃声。
标签: c++ pointers multiple-inheritance reinterpret-cast