为什么这行得通? (多重继承,切片)

Why does this work? (multiple inheritance, slicing)

考虑这个例子:

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

我比较好奇的是class C的assignB方法。 通常,我对类型转换的期望是 (B *) this 会将 this 类型转换为 B* 并因此覆盖 x 成员,而不是 y 。然而,这段代码恰恰相反:它 properly? 分配给 C.

的 B 部分

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

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

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

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

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