c++ - 为什么这三个指针值不一样?
黄舟
黄舟 2017-04-17 14:35:23
0
1
459
#include <iostream>
using namespace std;
class A
{
public:
    virtual void functionA() { }
};

class B
{
public:
    virtual void functionB() { }
};

class C :public A, public B
{

};

int main()
{
    C obj;
    A *pa = &obj;
    B *pb = &obj;
    C *pc = &obj;
    cout << pa << endl;
    cout << pb << endl;
    cout << pc << endl;

    return 0;
}  

我运行的结果是这样的:
00EFFBA8
00EFFBAC
00EFFBA8
也就是 pa 和 pc 是一样的,但是 pb 总是不一样,
我的问题是为什么三个指针值是不同的?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
洪涛

In clause 27 of the third edition of "effective c++", Scott Meyers said

There is an offset (offset) that is applied to the Derived* pointer during runtime to obtain the correct Base* pointer value.


In fact, this happens almost all the time once you use multiple inheritance, and it can happen even with single inheritance.

You can read the book

Here is the offset done by the compiler. Because the derived class inherits two pointers from the base class, and then uses the base class pointer to point to the derived class, the pointer is offset to the position of the base class in the derived class. The offset here is exactly the size of a pointer. distance.

You can add some variables in A. When using B's pointer to point to the derived class, the offset is equal to sizeof(A). But if there is an empty base class, the addresses may be the same, because the compiler will optimize the empty base class.


I never saw you accept the answer, (●ˇ∀ˇ●), haha

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template