2

考虑这个例子:

#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;
}

我很好奇的是assignBC 类的方法。通常,我对类型转换的期望是(B *) this类型转换thisB*并因此覆盖x成员,而不是y像它那样。然而,这段代码的作用恰恰相反:它正确吗?分配给 C 的 B 部分。

刚刚在 MSVC 2013 和 GCC 4.9.2 上测试过。两者的行为相同。

4

1 回答 1

2

这是因为指针因为多重继承而被调整。

如果您打印地址,这将是显而易见的

cout << (long long int)(this) << endl;
cout << (long long int)((B *)this) << endl;

还可以考虑使用 static_cast。在这种情况下,普通的 C 风格转换也可以。

于 2015-05-08T07:35:01.427 回答