提问人:mayank mahajan 提问时间:5/18/2022 更新时间:5/19/2022 访问量:608
“this”指针如何在 C++ 的继承中工作?
how does the 'this' pointer work in inheritance in c++?
问:
问题:
- 在下面的代码中,“this”指针指向基类和派生类中的不同内容,即使它在技术上包含相同的地址。为什么。
- 当“this”指针与继承一起使用时会发生什么。 (任何帮助将不胜感激,谢谢。
#include <iostream>
using namespace std;
// this pointer and inheritance.
class base {
public:
int x;
base() {
x = 10;
}
void func() {
cout<< this->x << endl; // 10
cout<< this << endl;
}
};
class derived : public base {
public:
int x;
derived() {
x = 20;
}
void func() {
cout<< this->x << endl; // 20
cout<< this << endl;
base::func();
}
};
int main () {
derived d;
d.func();
cout<< "execution complete.\n";
return 0;
}
output:
20
0x61ff18
10
0x61ff18
execution complete.
答:
- 在下面的代码中,“this”指针指向基类和派生类中的不同内容,即使它在技术上包含相同的地址。为什么。
类包含子对象。它们可以是基子对象,也可以是非静态数据成员。第一个子对象可以共享封装完整对象的内存地址:
|derived | < complete object
|base|x | < sub objects of derived
|x | < sub objects of base sub object
^
|
same address
- 当“this”指针与继承一起使用时会发生什么。
如果调用类的非静态成员函数,则指向该函数中的实例参数。this
如果调用派生对象的基的非虚拟非静态成员函数,将指向该函数中的基子对象。this
如果使用非限定查找调用类的虚拟非静态成员函数,它将调用该函数的最派生重写,并在该函数中指向派生该函数的对象。this
您的类包含两个整数。它们的名称如下:derived
this->base::x
和
this->derived::x
您似乎发现,您可以简单地键入以引用其中一个整数。this->x
编译器将根据上下文决定您引用的内容。在类中,你一定是说.在派生类中,假定您的意思是并且需要显式编写以告诉编译器您引用的是 中定义的。x
base
this->base::x
this->derived::x
this->base::x
int x;
base
“this”指针指向基类和派生类中的不同内容
事实并非如此。
this
没有指向 和 中的不同事物。这是一样的.base
derived
this
更改的含义,因为您的类有两个变量,它们都命名为 .this->x
x
程序中的类具有一个名为的成员函数,该函数隐藏了继承的同名成员函数。同样,该类也是一个名为 的数据成员,该成员隐藏了继承的具有相同名称的数据成员。derived
func
base
derived
x
base
现在,当你写道:
d.func(); //this calls the derived class member function `func` implicitly passing the address of `d` to the implicit `this` parameter
在上面的调用中,您调用了类的成员函数,同时将 的地址隐式传递给隐式参数。内部的类型是 。derived
func
d
this
this
func
derived
derived*
现在,在表达式的成员函数内部使用派生类的数据成员(而不是继承的成员),因为如上所述,它从基隐藏了继承的成员。因此,我们得到输出。func
derived
this->x
x
x
20
接下来,只需打印 .cout<< this << endl;
this
接下来,遇到调用表达式。还要注意,这相当于写 .这样做的效果是,它调用继承的成员函数,该函数由于派生类具有同名函数而隐藏。请注意,在此调用中,相同的地址被传递给基类的隐式参数。这次的区别在于,inside 的成员函数是 类型。base::func()
base::func()
this->base::func()
func
this
func
this
base
func
base*
现在,在 的成员函数中,in 表达式引用基类的数据成员,因此打印值 。因此,我们得到输出。func
base
x
this->x
x
10
10
最后,我们有 内部 的成员函数 ,它只是打印 .cout<< this << endl;
base
func
this
评论
derived
这里有 2 个。x
derived d;
main
int x;
struct x {int y;}; x z;
&z 和 &z.y 是相同的地址,但指向不同的东西