多重继承和this指针

时间:2011-12-25 14:32:33

标签: c++ this multiple-inheritance pod reinterpret-cast

假设我有这个结构:

struct vector_data
{
    double x, y;

    double& operator[](size_t index)
    {
        return * (static_cast<double*>(static_cast<void*>(this)) + index);
    }
};

operator []应该按预期工作,因为vector_data是POD类型。 预期的行为是vector_data [0]返回x,vector_data [1]返回y。

现在假设我有第二个结构:

struct more_data
{
    double evil_data;

    // There could be more here, data or functions
};

并且来自这两个:

struct composed : public more_data, public vector_data
{
};

这会破坏运营商[]的预期行为吗?换句话说,派生结构中的vector_data的this-pointer是否仍然指向struct的vector_data部分,还是指向派生结构的开头?

如果它确实破坏了operator [],那么我该如何解决这个问题呢?我可以先从vector_data继承,但假设compos包含虚函数。我知道大多数编译器都将vtable放在最后,但这并不能保证。什么是最好的方法?

2 个答案:

答案 0 :(得分:6)

不考虑错误指针算术的问题(在xy之间填充的可能性使您的假设无效),这里是this指针发生的快速说明当您使用多重继承时:

#include <iostream>
using namespace std;

struct a {
    int aa;
    void showA() {
        cerr << this << endl;
    }
};
struct b {
    int bb;
    void showB() {
        cerr << this << endl;
    }
};
struct c : public a, b {
    int cc;
    void showC() {
        cerr << this << endl;
    }
};
int main() {
    c x;
    x.showA();
    x.showB();
    x.showC();
}

showAshowB打印不同的数字; showC打印与showA相同的数字,因为a首先列在基本列表中。如果您在其中切换ab,那么showCshowB将是相同的。 “魔术”在C ++编译器中:它足够聪明,可以为每个成员函数提供正确的this指针。

答案 1 :(得分:1)

你想要的可能是:

struct vector_data
{
   union 
   {
        struct 
        {
            double x, y;
        }; 
        double data[2];
   }; 

   double& operator[](size_t index)
   {
       return data[index];
   }
}