【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;
}
相关推荐
Xy-unu2 分钟前
[LLM]AIM: Adaptive Inference of Multi-Modal LLMs via Token Merging and Pruning
论文阅读·人工智能·算法·机器学习·transformer·论文笔记·剪枝
Hcoco_me3 分钟前
算法选型 + 调参避坑指南
算法
Jul1en_8 分钟前
【算法】分治-归并类题目
java·算法·leetcode·排序算法
kangk129 分钟前
统计学基础之概率(生物信息方向)
人工智能·算法·机器学习
再__努力1点9 分钟前
【77】积分图像:快速计算矩形区域和核心逻辑
开发语言·图像处理·人工智能·python·算法·计算机视觉
唯唯qwe-24 分钟前
Day22: 贪心算法 | 区间问题,左/右端点排序
算法·贪心算法
Hcoco_me36 分钟前
LLM(Large Language Model)系统学习路线清单
人工智能·算法·自然语言处理·数据挖掘·聚类
java修仙传41 分钟前
力扣hot100:寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
胖咕噜的稞达鸭1 小时前
算法日记专题:位运算II( 只出现一次的数字I II III 面试题:消失的两个数字 比特位计数)
c++·算法·动态规划
茉莉玫瑰花茶1 小时前
ProtoBuf - 3
服务器·c++·protobuf