小编Lin*_*ang的帖子

“this”在父类(c++)中指向哪里?

我有一个关于 C++ 编程的问题。如果我有两个类,分别称为父类和子类。孩子是从父母派生出来的。当我在堆栈或堆上创建对象时,它必须由两个类的构造函数初始化。我发现如果您在调试时进入构造函数,“this”ptr 会指向不同的地址。子类的“this”指向对象,但是父类的“this”指向什么?

这是我的代码供参考。仅供参考:我在 Ubuntu 20.04 上使用 g++ 10.3 和 gdb 9.2

#include <iostream>

class parent
{
public:
    int attribute0, attribute1, attribute2, attribute3;
    parent():attribute0(0), attribute1(1), attribute2(2), attribute3(3){}
};
class child : parent
{
public:
    int attribute4;
    child(int arg) : parent() {
        attribute4 = arg;
    }
};

int main(){
    auto obj0 = new child(100);
    delete obj0;

    child obj1(80);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ this

1
推荐指数
1
解决办法
997
查看次数

标签 统计

c++ ×1

this ×1