C++ - this 指针

2016-01-15  本文已影响122人  Mitchell
//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
上一篇 下一篇

猜你喜欢

热点阅读