一个c++里类的问题Time temp(*this);中的(*this)是什么意思

来源:百度知道 编辑:UC知道 时间:2024/05/26 08:12:33
Time是一个类,
Time temp(*this);
.......

后面有语句
return temp;

请问
Time temp(*this);中的(*this)是什么意思,它起什么作用?

this成员是指向调用该函数的对象
*this就是指这个对象本身了

这里是用拷贝构造函数利用自身构造对象temp。

this是类成员函数所在的对象的指针,*this就是这个对象本身

比如:

#include <iostream>
using namespace std;

class A
{
int myInt;
A( int init )
{
myInt = init;
}

void func_A()
{
(*this).func_B();
}

void func_B()
{
cout << this->myInit;
}
};

其中 (*this).func_B(); 和直接调用 func_B();等效
cout << this->myInit;和cout << myInit;等效.

但是,this指针只能在非static成员函数中使用,因为只有非static成员函数可以访问对象本身