我有一个关于 C++ 派生类中的“this”指向什么的问题。
class A
{
int a;
public:
void funca() { cout << this << endl; }
};
class B
{
int b;
public:
void funcb() { cout << this << endl; }
};
class Derived : public A, public B {};
int main() {
Derived d;
d.funca();
d.funcb(); // prints 4bytes more than the above.
}
在这种情况下,基类中的“this”在派生类中如何解释? 是派生类的this还是基类的this?? 从输出来看,我认为这指向使用它的类对象。我说得对吗?
最佳答案
如何在派生类中解释基类中的“this”?
我想问题应该是基类如何驻留在派生类中
当一个类被另一个类继承时,编译器会将基类的成员放在派生类中。 this
总是引用实际对象,你是对的。 d.funcb();
提前打印 2 个字节,因为 B
的成员在 Derived
的 A
的 4 个字节之后开始>。这 4 个字节由 A::a
成员变量占用。但是布局和内存模型并不能保证,并且会因编译器而异。 Derived
的一种可能的内存布局可能是
Members of A (4 byte in this case for a)
Members of B (4 byte in this case for b)
Members of Derived (if any)
所以派生类没有基类“this”,只有一个this
,它引用了实际的对象。派生类获取其中基类成员的拷贝。
关于c++ - C++ 派生类中的 this 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23827148/