c++ - C++ 派生类中的 this 值

标签 c++ inheritance this derived

我有一个关于 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 的成员在 DerivedA 的 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/

相关文章:

java - 当我在 "player object"上使用名为 movePosition() 的方法时,它会更改由该类创建的所有其他对象的 x 位置

C#:通用继承工厂

c# - 扩展方法与继承

Android Toast 上下文难题

c++ - glm 设置对象位置

c++ - 我可以在继承自 QObject 的同时使用 QSharedData 吗?

c++ - 原始套接字未接收 ARP 请求

c++ - 逆变类型和可扩展性

c++ - 返回嵌套对象的成员有什么惩罚吗?

javascript - object.watch(), 获取新值