Lecture 04 “this”指针
类的每一个成员函数(静态成员函数除外)都有一个隐藏的形参this,其类型为该类对象的指针;在成员函数中对类成员的访问是通过this来进行的。例如,
-
对于前面A类的成员函数g:
void g(int i) { x = i; }
-
编译程序将会把它编译成:
void g(A *const this, int i) { this->x = i; };
当通过对象访问类的成员函数时,将会把相应对象的地址传给成员函数的this参数。例如,
- 对于下面的成员函数调用:
a.g(1);
和b.g(2);
- 编译程序将会把它编译成:
g(&a,1);
和g(&b,2);
一般情况下,类的成员函数中不必显式使用this指针,编译程序会自动加上。
但如果成员函数中要把this所指向的对象作为整体来操作,则需要显式地使用this指针。例如:
void func(A *p);
class A
{ int x;
public:
void g(int i) { x = i; func(this); }
......
};
......
A a,b;
a.g(1); //要求在g中调用func(&a)
b.g(2); //要求在g中调用func(&b)
用C语言实现C++的类
一个C++程序
class A
{ int x,y;
public:
void f();
void g(int i) { x = i; f(); }
};
......
A a,b;
a.f();
a.g(1);
b.f();
b.g(2);
功能上与前面C++程序等价的C程序
struct A
{ int x,y;
};
void f_A(struct A *this);
void g_A(struct A *this, int i)
{ this->x = i;
f_A(this);
}
......
struct A a,b;
f_A(&a);
g_A(&a,1);
f_A(&b);
g_A(&b,2);
结论:
面向对象是一种程序设计思想,用任何语言都可以实现!
采用面向对象语言会使得面向对象程序设计更加容易,语言也能提供更多的面向对象保障!