成員函數中this是指向正在調用該函數的對象,this指正在創建對象內部的成員。同一個類中的函數可以通過this相互調用,普通函數不能通過this調用構造函數,但構造函數可以通過this訪問普通函數!
.h文件
ifndef TEACHER_H_
#define TEACHER_H_
class Teacher {
public:
int age;
int no;
Teacher();
~Teacher();
void teach1();
void teach2();
};
#endif /* TEACHER_H_ */
.cpp文件
#include "Teacher.h"
#include <iostream>
using namespace std;
Teacher::Teacher() {
}
Teacher::~Teacher() {
}
//成員函數中this是:
//指向正在調用該函數的對象
void Teacher::teach1() {
cout<<this->age<<endl;
this->teach2();
}
void Teacher::teach2() {
cout<<this->age<<endl;
}
.main文件
#include <iostream>
using namespace std;
#include "Teacher.h"
void f1() {
Teacher t1;//age no //創建的t1對象,this指向t1中的成員
t1.age = 100;
t1.teach1();//100
Teacher t2; //創建的是t2對象,this指向t2中的成員
t2.age = 200;
t2.teach1();//200
}
void f2() {
Teacher t1;//age=100
t1.age = 100;
Teacher *p1 = &t1; //p1指向的是t1對象,所以調用的是teach1()是t1中的!
p1->teach1();//100
}
void f3() {
Teacher t1;//age=100
t1.age = 100;
Teacher &r = t1; r指向的t1,調用的還是t1中的teacher1()
r.teach1();//100
}
int main() {
f3();
return 0;
}