myCar.Modify();这样通过一个对象调用成员函数的语句,又该如何翻译呢?myCar.Modify();这样的语句也只能被翻译成普通的调用全局函数的语句。那如何让翻译后的 Modify 全局函数还能作用在 myCar 这个结构变量上呢?答案就是引入“this 指针”。下面来看一段 C++ 程序到C 程序的翻译。
class CCar
{
public:
int price;
void SetPrice(int p);
};
void CCar::SetPrice(int p)
{
price= p;
}
int main()
{
CCar car;
car.SetPrice(20000);
return 0;
}
翻译后的C程序(此程序应保存为扩展名为 .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;
}
可以看出,类被翻译成结构体,对象被翻译成结构变量,成员函数被翻译成全局函数。但是C程序的全局函数 SetPrice 比 C++ 的成员函数 SelPrice 多了一个参数,就是struct CCar *this。car.SetPrice(20000);被翻译成SetPrice(&car, 20000);,后者在执行时,this 形参指向的正是 car 这个变量,因而达到了 SetPrice 函数作用在 car 变量上的效果。
#include <iostream>
using namespace std;
class A
{
int i;
public:
void Hello(){ cout << "hello" << endl; }
};
int main()
{
A* p = NULL;
p -> Hello();
}
程序的输出结果是:P->Hello()实质上应该是Hello(p),在翻译后的 Hello 函数中,cout 语句没有用到 this 指针,因此依然可以输出结果。如果 Hello 函数中有对成员变量的访问,则程序就会出错。
#include <iostream>
using namespace std;
class Complex {
public:
double real, imag;
Complex(double r, double i) : real(r), imag(i) {}
Complex AddOne()
{
this->real++;
return *this;
}
};
int main()
{
Complex cl(1, 1), c2(0, 0);
c2 = cl.AddOne();
cout << c2.real << "," << c2.imag << endl; //输出 2,1
return 0;
}
第 9 行,this 指针的类型是 Complex*。因为 this 指针就指向函数所作用的对象,所以 this->rear 和 real 是完全等价的。*this代表函数所作用的对象,因此执行第 16 行,进入 AddOne 函数后,*this实际上就是 c1。因此的 c2 值会变得和 c1 相同。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有