基本概念:
C++刚出来的时候没有相应的编译器,因此要编译的时候要先翻译成C程序再进行编译。C++中的class对应C中的结构体,而结构体中不能存放函数,所以class中的成员函数被翻译成C中的全局函数,而这个全局函数又需要class中的成员变量(也就是struct中的变量),所以在调用的时候需要传入结构体的指针,这个指针就是this指针。
实例:
1 class Complex { 2 public: 3 double real, imag; 4 void Print() { cout << real << "," << imag; } 5 Complex(double r, double i) :real(r), imag(i) {}; 6 Complex AddOne() { 7 this->real++; 8 this->Print(); 9 return *this;//这里调用了默认的复制构造函数 10 } 11 }; 12 int main() { 13 Complex c1(1, 1), c2(0, 0); 14 c2 = c1.AddOne();//传入C1的指针 15 return 0; 16 } 17 18 /* 19 输出: 20 2,1 21 */
1 class A { 2 public: 3 int i; 4 void Hello() { cout << "hello" << endl; }//因为这个函数并没有用到class中其他成员变量,所以并不会报错 5 }; 6 int main() { 7 A *p = NULL; 8 p->Hello();//传入NULL指针 9 return 0; 10 } 11 12 /* 13 输出: 14 hello 15 */
this指针与静态成员函数:
- 静态成员函数中不能使用this指针
- 因为静态成员函数并不具体作用于某个对象
- 因此,静态成员函数的真实的参数的个数就是程序中写出的参数个数