【C++】5___this指针

发布于:2024-12-07 ⋅ 阅读:(54) ⋅ 点赞:(0)

目录

一、this指针

 二、空指针访问成员函数

三、const修饰成员函数


一、this指针

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

作用

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

 代码示例

#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指针

 代码示例

#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. 常对象只能调用常函数

 代码示例

#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;
}