多继承和this指针 [英] Multiple inheritance and the this pointer
问题描述
假设我有这个结构:
struct vector_data
{
double x, y;
double& operator[](size_t index)
{
return * (static_cast<double*>(static_cast<void*>(this)) + index);
}
};
运算符[]应该按预期工作,因为vector_data是POD类型。
预期的行为是vector_data [0]返回x,vector_data [1]返回y。
The operator[] should work as expected, because vector_data is a POD type. The expected behaviour is that vector_data[0] returns x, and vector_data[1] returns y.
现在假设我有一个第二个结构:
Now suppose I have a second struct:
struct more_data
{
double evil_data;
// There could be more here, data or functions
};
并从这两者派生:
struct composed : public more_data, public vector_data
{
};
这会破坏operator []的预期行为吗?换句话说,派生结构中的vector_data的this指针仍然指向struct的vector_data部分,还是指向派生结构的开始?
Will this destory the expected behaviour of operator[]? In other words, will the this-pointer of vector_data in the derived struct still point to the vector_data part of the struct, or will it point to the beginning of the derived struct?
如果它破坏operator [],那么我该如何解决这个问题呢?我可以先从vector_data继承,但假设组成包含虚函数。我知道大多数编译器把vtable放在最后,但这不是保证。
If it does destroy operator[], then how can I resolve this problem? I can inherit from vector_data first, but suppose composed contains virtual functions. I know most compilers put the vtable at the end, but this is not guaranteed. What would be the best approach?
推荐答案
忽略指针算术不正确的问题(在<$ c之间填充的可能性$ c> x 和 y
使你的假设无效),这里是一个快速说明 code>指针当您使用多重继承:
Leaving aside the issues of your incorrect pointer arithmetics (the possibility of padding between x
and y
invalidates your assumption), here is a quick illustration of what's going on with this
pointer when you use multiple inheritance:
#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();
}
showA
code> showB 打印不同的数字; showC
输出与 showA
相同的数字,因为 a
列在基地名单的第一位。如果您切换 a
和 b
,那么 showC
showB
将是相同的。 magic是在C ++编译器:它是聪明到足以给每个成员函数一个正确的这
指针。
showA
and showB
print different numbers; showC
prints the same number as showA
, because a
is listed first in the list of bases. If you switch a
and b
there, then showC
and showB
would be the same. The "magic" is in the C++ compiler: it is smart enough to give each member function a correct this
pointer.
这篇关于多继承和this指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!