考虑这个例子:
#include <iostream>
using namespace std;
class A
{
public:
int x;
};
class B
{
public:
int y;
B() { y = 0; }
B(int var): y(var) {}
};
class C : public A, public B
{
public:
void assignB(B x)
{
*(B *)this = x; // <-- why does this properly assign B?
}
};
int main() {
C test;
test.x = 5;
test.y = 10;
test.assignB(B(2));
cout << "x " << test.x << endl;
cout << "y " << test.y << endl;
return 0;
}
我很好奇的是assignB
C 类的方法。通常,我对类型转换的期望是(B *) this
类型转换this
为B*
并因此覆盖x
成员,而不是y
像它那样。然而,这段代码的作用恰恰相反:它正确吗?分配给 C 的 B 部分。
刚刚在 MSVC 2013 和 GCC 4.9.2 上测试过。两者的行为相同。