this指针的使用(P138)

/*

    当调用一个成员函数时,系统自动转向它传递一个隐含的参数。该参数是一个指向调用该函数的对象的指针,称为this指针,从而使成员函数知道对哪个对象进行操作。

    类的每个成员函数中都包含this这个特殊的指针,它指向本类对象,值为当前被调用的成员函数所属对象的起始地址。

友元函数不通过对象调用,所以没有this指针

静态成员函数没有this指针

*/

#include<iostream>
using namespace std;
class myComplex
{
public:
double real,imag;
myComplex():real(0),imag(0){}
myComplex(double,double);
myComplex AddRealOne();
myComplex AddImagOne();
void outCom(); //成员函数,输出调用者对象的有关数据
};

myComplex::myComplex(double real,double imag)
{
this->real = real;
this->imag = imag;
}
void myComplex::outCom()
{
cout<<"("<<real<<","<<imag<<")";
}
myComplex myComplex::AddRealOne()
{
this->real++;
return *this; //返回对象本身
}
myComplex myComplex::AddImagOne()
{
this->imag++;
return *this; //返回对象本身
}

int main()
{
myComplex c1(1,1),c2,c3;
c1.outCom();
c2.outCom();
c3.outCom();
cout<<endl<<"我是分界线"<<endl;
c2=c1.AddRealOne();
c1.outCom();
c3=c1.AddImagOne();
c2.outCom();
c3.outCom();
cout<<endl;
return 0;
}

posted @ 2020-03-10 21:18  CollisionDimension  阅读(149)  评论(0)    收藏  举报