C++中this指针的详解:

成员函数中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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值