#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 总是不一样,
我的问题是为什么三个指针值是不同的?
In clause 27 of the third edition of "effective c++", Scott Meyers said
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