【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;
}
相关推荐
apocelipes17 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
HjhIron19 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩20 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者2 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法