2016-02-22 57 views
2

我想知道是否有可能找到具有多重繼承的對象中的結構的偏移量而不知道任何類型的成員的。我知道的類型,如果有幫助。多重繼承中的類型偏移

我使用sizeof()目前計算偏移。當我有一個空的基類時存在問題,或者在爲兩個繼承組合兩個類時添加了填充。

讓我用一個例子說明問題:

struct A { int x; }; 
struct B { bool b; }; // Empty struct gives same results 
struct C : B, A {}; 

int main() 
{ 
    // Prints: 4 1 8 
    printf("%i %i %i\n", sizeof(A), sizeof(B), sizeof(C)); 

    C obj; 
    obj.x = 1; 
    obj.b = true; 

    // Simple offset calculations, I can't use these because they both use data members 
    // Prints: 4 4 
    printf("%i %i\n", (int)&obj.x - (int)&obj, offsetof(C, x)); 

    // Cast to pointer 
    char* ptr = reinterpret_cast<char*>(&obj); 
    A* wrong = reinterpret_cast<A*>(ptr + sizeof(B)); 

    // Prints wrong values because sizeof(B) == 1 wrongly offsets the pointer 
    printf("%i\n", wrong->x); 

    // Because of padding this is correct 
    // Empty base class optimization would simply cast ptr as correct 
    // How to get the correct offset? 
    A* correct = reinterpret_cast<A*>(ptr + 4); 

    // Prints correct value, 1 
    printf("%i\n", correct->x); 
} 
+1

'%zu'是'printf中 –

+1

sizeof'格式說明我不知道到底是什麼你'請問,但也許'reinterpret_cast (static_cast (&obj)) - reinterpret_cast (&obj);' –

回答

0

使用

reinterpret_cast<char *>(static_cast<A *>(&obj)) - reinterpret_cast<char *>(&obj);