//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;
}
- 作用就是指向成員函數(shù)所作用的對(duì)象
class Complex{
public:
double real,image;
void Print(){cout<<real<<","<<imag;}
Complex(double r,double i):real(r),image(i){ }
Complex AddOne(){
this->real++;//等價(jià)于 real++
this->Print();//等價(jià)于 Print
return * this;//返回作用的對(duì)象
}
};
int main(){
Complex c1(1,1),c2(0,0);
c2 = c1.AddOne();
return 0;
}
//這個(gè)函數(shù)不會(huì)出錯(cuò)
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
//這樣就會(huì)出錯(cuò)
classs A
{
int i;
public:
void Hello(){cout<<"i"<<"hello"<<endl;}
};->void Hello(A * this){out<<this->i<<"hello"<<endl;}
//this 若為 NULL自赔,則出錯(cuò)J桥俊岩睁!
int main()
{
A * p = NULL;
p->Hello();->Hello(p);
}//輸出: hello
- 在類(lèi)的非靜態(tài)成員函數(shù)中驯镊,C++ 的函數(shù)都會(huì)默認(rèn)多出一個(gè)參數(shù)就是 this 指針凑懂,指向的是他所對(duì)應(yīng)的對(duì)象。
-
注意:
- 靜態(tài)成員函數(shù)中不能使用this 指針虽惭!
- 因?yàn)殪o態(tài)成員函數(shù)并不具體作用于某個(gè)對(duì)象橡类!
- 因此,靜態(tài)成員函數(shù)的真實(shí)的參數(shù)個(gè)數(shù)芽唇,就是程序中寫(xiě)出的參數(shù)個(gè)數(shù)顾画!
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者