//C++
class CCar{
public:
int price;
void SerPrice(int p);
};
void CCar::SetPrice(int p){price = p;}
int main(){
CCar car;
car.SetPrice(20000);
return 0;
}
//C
struct CCar {
int price;
};
void SetPrice(struct CCar*this int p)
{ this->price = p;}
int main(){
struct CCar car;
SetPrice(&car,20000);
return 0;
}
class Complex{
public:
double real,image;
void Print(){cout<<real<<","<<imag;}
Complex(double r,double i):real(r),image(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;
}
//这个函数不会出错
classs A
{
int i;
public:
void Hello(){cout<<"hello"<<endl;}
};->void Hello(A * this){out<<"hello"<<endl;}
int main()
{
A * p = NULL;
p->Hello();->Hello(p);
}//输出: hello
//这样就会出错
classs A
{
int i;
public:
void Hello(){cout<<"i"<<"hello"<<endl;}
};->void Hello(A * this){out<<this->i<<"hello"<<endl;}
//this 若为 NULL,则出错!!
int main()
{
A * p = NULL;
p->Hello();->Hello(p);
}//输出: hello
- 在类的非静态成员函数中,C++ 的函数都会默认多出一个参数就是 this 指针,指向的是他所对应的对象。
-
注意:
- 静态成员函数中不能使用this 指针!
- 因为静态成员函数并不具体作用于某个对象!
- 因此,静态成员函数的真实的参数个数,就是程序中写出的参数个数!