我有一个关于 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)
\n\n\xe2\x80\x9cthis\xe2\x80\x9d 指向父类(c++)中的哪里?
\n
在所有成员函数中,this总是指向其成员函数被调用的对象。这与类型层次结构无关。在基类的成员函数中,this指向基类子对象。