this指针的使用[C++][code]

this指针详解
本文介绍了C++中this指针的概念及其使用方式。this指针指向调用非静态成员函数的对象,用于访问对象的数据成员。文章通过示例展示了如何利用this指针返回当前对象,以及在特定场景下使用this指针的必要性。
/**//*
 * 1. this指针保存了用来调用非静态成员函数的对象的地址
 * 2. 在调用函数时,每个非静态成员函数名都必须前置对象名。该对象的地址被传递给函数,并且保存在
 *    this指针中。为了访问保存在对象中的数据,函数需要使用保存在this指针中的对象的地址
 * 3. this指针的类型就是其地址保存在this指针中的对象的所属类的类型,如下例中的 Pixel * /const Pixel *
 * 4. 大多数情况下没必要使用this指针,但有些情况需要返回使用的对象以便调用函数。因为对象是通过
 *    this指针隐式传递的,因此为了返回对象,需要显式地使用this指针,如:return *this;
 *
 * 注意:1. 每一个非静态成员函数都有一个由C++编译器创建的隐式参数,即this指针。
 *       2. 友元函数和静态函数没有this指针
 *       3. 在返回用来调用非静态成员函数的对象时,应该显式地使用this指针
 
*/

#include 
<iostream>
using namespace std;

class Pixel
{
    
int x, y;
public:
    Pixel() : x(
0), y(0{ cout<<"\t \tPixel created! "<<endl; } 
    
~Pixel() { cout<<"\t \tPixel destroyed! "<<endl; }
    
void setCoord(int x1, int y1) { x=x1; y=y1; }
    
void getCoord()
    
{
        cout
<<"Pixel's coordinates: "<<endl;
        cout
<<"X="<<x<<" Y="<<y<<endl;
    }

    Pixel move_10()
    
{
        x
+=10; y+=10return *this;
    }

}
;

void main()
{
    Pixel p1, p2;
    
int x1, y1;
    cout
<<" Enter X and Y coordinates:";
    cin
>>x1>>y1;

    p1.setCoord(x1, y1);
    p1.getCoord();

    p2
=p1.move_10();//call copy constructor
    p2.getCoord();
    p1.getCoord();
}

运行结果:
                Pixel created!
                Pixel created!
 Enter X and Y coordinates:39 44
Pixel's coordinates:
X=39 Y=44
                Pixel destroyed!
Pixel's coordinates:
X=49 Y=54
Pixel's coordinates:
X=49 Y=54
                Pixel destroyed!
                Pixel destroyed!
Press any key to continue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值