C++编译器对类的编译流程
(1)找到成员属性(类型,成员名)
(2)识别方法声明(识别函数原型)
(3)改写方法:在每个方法的第一个形参前面添加个 该类的一个this指针(类名* const this)
例如:
1 2 3 4 5 6 7 8 9 10 11 12
| #include <iostream> using namespace std; class Person { public: Person(); ~Person(); Person(char* _name, int _age); private: int age; char* name; };
|
改写前:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Person::Person() :age(0), name(new char[20]) {}
Person::Person(char* _name, int _age) :name(new char[20]) { if(_name == NULL || age < 0) return; strcpy(name, _name); age = _age; } Person::~Person() { if(name != NULL) { delete[] name; age = 0; } }
|
改写后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| Person::Person(Person* const this) :age(0), name(new char[20]) {}
Person::Person(Person* const this, const char* _name, int _age) :name(new char[20]), age(0) { if(_name == NULL || age < 0) return; strcpy(this->name, _name); this->age = _age; } Person::~Person(Person* const this) { if(name != NULL) { delete[] this->name; this->age = 0; } }
|
(4)调用对象成员方法时:编译器改成面向过程的形式
编译器改前:
1 2 3 4 5 6 7 8 9 10
| int main() { Person p1("jiege", 21); Person p2("yueyue", 20);
p1.~Person(); p2.~Person(); return 0; }
|
编译器改后:1 2 3 4 5 6 7 8 9 10
| int main() { Person p1("jiege", 21); Person p2("yueyue", 20);
~Person(&p1); ~Person(&p2); return 0; }
|
想必在看完上面的编译器编译流程后,你已经对this指针以及C++的对象模型有了一定的理解吧。后面再详细讲this指针相关内容。