【C++】5___this指针

目录

一、this指针

二、空指针访问成员函数

三、const修饰成员函数


一、this指针

this指针指向被调用的成员函数所属的对象
作用

  • 形参和成员变量同名时,可以用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this

代码示例

cpp 复制代码
#include<iostream>
using namespace std;

class person{
	
public:
	
	person(int age){
		this->age = age; //解决名称冲突
	}
	
	person& personAddAge(person &p){
		this->age += p.age; 
		return *this;
	}
	
	int age;
};

void test(){
	person P1(10);
	cout<<"P1.age="<<P1.age<<endl;
	
}

void test2(){
	person p1(10);
	
	person p2(10);
	p2.personAddAge(p1).personAddAge(p1).personAddAge(p1);
	cout<<"p2.age="<<p2.age<<endl;	
}

int main(){
	
	test();
	test2();
	return 0;
}

二、空指针访问成员函数

空指针也可以调用成员函数,但要注意有没有用到this指针

代码示例

cpp 复制代码
#include<iostream>
using namespace std;

class person{
	
public:
	
	void fun(){
		cout<<"fun函数调用"<<endl;
	}
	
	void fun2(){
		if(this == NULL){  // 保证代码健壮性
			return;
		}
		//  报错原因是传入了空指针
		cout<<"age="<<age<<endl;  // age  ===  this->age
	}
	int age;
};

void test(){
	person *p = NULL;
	p->fun();  // 可以调用
	p->fun2();  // 错误
	
}

int main(){
	
	test();
	return 0;
}

三、const修饰成员函数

  • 常函数
  1. 成员函数后加const 变为常函数
  2. 函数内不可修改成员属性
  3. 成员属性声明是在前面加上mutable后,在常函数中依然可以修改
  • 常对象
  1. 声明对象前加const,称为常对象
  2. 常对象只能调用常函数

代码示例

cpp 复制代码
#include<iostream>
using namespace std;

class person{
	
public:
	// 常函数
	void fun() const {  // 在成员函数后面加const,修饰的是this指向,让指针指向的值也不可以修改
//		age = 10; // 错误,this指针的本质  是指针常量,指针的指向是不可以修改的
	b = 10;
	}
	
	int age;
	mutable int b; // 特殊变量,即使在常函数中也可以修改。加关键字mutable
};

int main(){
	return 0;
}
相关推荐
多米Domi01135 分钟前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
_F_y7 小时前
MySQL用C/C++连接
c语言·c++·mysql
兩尛7 小时前
c++知识点2
开发语言·c++
xiaoye-duck7 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Azure_withyou8 小时前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月8 小时前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
L_09079 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
A_nanda9 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
代码雕刻家11 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
Ulyanov11 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲