C++笔记9

this指针##

C++翻译成C

class CCar{
public:
int price;
void SetPrice(int p);
};
void CCar::SetPrice(int p)
{price=p;}
int main(){
CCar car;
car.SetPrice(20000);
return 0;
}
struct CCar{
int price;
};
void SetPrice(struct CCar*this,int p)
{this->price=p;}
int main(){
struct CCar car;
SetPrice(&car,20000);
return 0;
}

·其作用就是指向成员函数所作用的对象
exp.

class Complex{
public:
double real,imag;
void Print(){cout<<real<<","<<imag;}
Complex(double r,double i):real(r),imag(i)
{  }
Complex AddOne() {
this->real++;//等价于real++
this->Print();//等价于Print
return *this;
}
};
int main(){
Complex c1(1,1),c2(0,0);
c2=c1.AddOne();
return 0;
}
输出2,1

再举一个例子进一步说明
exp.

class A
{
int i;
public:
void Hello(){cout<<"hello"<<endl;}
};->void Hello(A*this){cout<<"hello"<<endl;}
int main()
{
A*p=NULL;//定义p这个空指针
p->Hello();->Hello(p) //调用Hello,让Hello作用在p所指向的对象上,用空指针调用Hello
};

exp.

class A
{
int i;
public:
void Hello(){cout<<i<<"hello"<<endl;}
};->void Hello(A*this){cout<<this->i<<"hello"<<endl;}this相当于空指针p,也就是NULL,要找这个空指针所指向对象里的i当然找不到
int main()
{
A*p=NULL;
p->Hello();->Hello(p) 
};

静态成员函数不能使用this指针
因为静态成员函数并不具体作用于某个对象
因此静态成员函数的实参的个数,就是程序中写出的参数个数
普通成员函数的参数个数比写出来的多

posted @ 2020-02-06 13:59  AirBirdDD  阅读(73)  评论(0)    收藏  举报