I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
/*
 * 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
posted on 2008-03-06 21:35  jcsu  阅读(1096)  评论(0编辑  收藏  举报