this指针就是指向调用成员函数的对象,比如下面这个类
class stock
{
private :
std :: string company;
long shares;
double share_val;
double total_val;
void set_tot()
{
total_val = shares * share_val;
}
public :
stock();
~stock();
stock(const std :: string & co , long n = 0 , double pr = 0.0 );
void show() const;
const stock& topval(const stock& s) const;
};
stock :: stock()
{
std :: cout << "Default constructer called \n";
company = "no name";
shares = 0 ;
share_val = 0.0;
total_val = 0.0;
}
stock :: stock(const std :: string & co , long n , double pr)
{
company = co;
if(n < 0 )
{
std :: cout << "Number of shares can't be negative"
<< company << "shares set to 0 .\n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot() ;
}
stock :: ~stock()
{
cout << "bye" << company << endl;
}
如果我有一个stock对象名为food,那么我想调用food对象中的show()成员函数,那么这个时候的this就是指向food,这个this指针只能在成员函数中使用,如果在主函数中使用的话代表会产生歧义.
this指针的好处有不少,比如你要比较两个对象中的某个值的大小,我们会定义一个比较大小的函数:topval(),编写的程序如下
const stock& stock :: topval(const stock& s) const
{
if(s.total_val > total_val)
return s;
else
return ?;
}
如果是参数大,自然就是返回一个s对象没有问题,但是如果调用函数的对象大,怎么办?利用this指针就能完美解决,返回*this不就是调用整个调用成员函数的对象嘛,如下
const stock& stock :: topval(const stock& s) const
{
if(s.total_val > total_val)
return s;
else
return ?;
}
测试下一下
int main ()
{
stock food("KFC" , 2 , 2.0);
stock juice("coco" , 3 , 3.0);
food.topval(juice).show();
return 0;
}
运行结果: