为什么这样做? (多重继承,切片)

时间:2015-05-08 07:29:55

标签: c++ multiple-inheritance object-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;
}

我很好奇C类的assignB方法。 通常,我对类型转换的期望是(B *) thisthis转换为B*并因此覆盖x成员,而不是覆盖y成员。但是,这段代码恰恰相反:正确?分配给C的B部分。

刚刚在MSVC 2013和GCC 4.9.2上测试过。两者表现相同。

1 个答案:

答案 0 :(得分:2)

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

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

UIGestureRecognizer

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

相关问题