C++ | 期末冲刺版②

目录

this指针

空指针返回成员函数

 const修饰成员函数

 友元

全局函数做友元

类做友元

成员函数做友元


this指针

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

(谁调的,this就指向谁)

this指针的用途

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this
Person(int age)
	{
		//this指针指向的是被调函数的成员函数所属的对象
		//这里指向的就是p
		this->age = age;
	}
	//返回本体要用应用的方式进行返回
	//这里返回值如果是Person,就创建了一个新的对象
	Person& PersonAddPerson(Person &p)
	{
		this->age += p.age;
		return *this;
	}

空指针返回成员函数

void ShowPersonAge()
	{
	
		//提高健壮性,空的就直接返回,防止代码崩溃
		if (this == NULL)
		{
			return;
		}
		//报错原因是因为传入的指针是NULL——无中生有,用一个空指针访问里面的属性 
		cout << this->m_Age << endl;
	}

 const修饰成员函数

void showPerson() const//加个const就不允许修改了
	{
		this->m_b = 100;
		//this = NULL;tbhis指针是不可以修改指针的指向的
	}
	mutable int m_b;//加了mutable修饰的特殊变量,即使在常函数,常对象中,也可以修改这个值

这段代码有两个错误:

1. `this` 是一个指向当前对象的指针,不能被赋值为 `NULL`。

2. `const` 成员函数不能修改对象的成员变量,因此不能修改 `m_b` 的值。

如果你想要将 `showPerson()` 函数设置为 `const` 成员函数,应该将其修改为:

```
void showPerson() const
{
    // 只能访问对象的成员变量,不能修改
    int a = this->m_a;
    int b = this->m_b;
    std::cout << "a = " << a << ", b = " << b << std::endl;
}
```

如果你想要修改对象的成员变量,应该将 `showPerson()` 函数设置为非 `const` 成员函数,应该将其修改为:

```
void showPerson()
{
    this->m_b = 100;
}

 友元

全局函数做友元


class Building 
{
	//goodgay全局函数是Building类的一个好朋友,可以访问你家的卧室(私有成员)
	friend void goodgay(Building* building);
public:
	Building()
	{
		m_SittingRoom = "客厅";
		m_BedRoom = "卧室";
	}
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

//全局函数
void goodgay(Building* building)
{
	cout << "好基友全局函数正在访问你的" << building->m_SittingRoom << endl;
	
	cout << "好基友全局函数正在访问你的" << building->m_BedRoom << endl;
}


类做友元

一个类在另一个中friend class xx。

#include<iostream>
#include<string>
using namespace std;
//在前面先声明一下
class Building;

class GoodGay
{
public:
	GoodGay();
public:
	void visit();//参观函数 访问Building中的属性
	Building* building;
};


class Building
{
	//GoodGay是Building类的好朋友,可以访问其私有属性
	friend class GoodGay;
public:
	Building();
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

void GoodGay::visit()
{
	cout << "好基友正在访问你的" << building->m_SittingRoom << endl;
	cout << "好基友正在访问你的" << building->m_BedRoom << endl;
}


成员函数做友元

告诉编译器 另一个类中的xx成员函数作为本类的好朋友,可以访问私有函数。



class Building;
class GoodGay
{
public:
	GoodGay();
	void visit();//可以访问Building中私有成员
	void visit1();//不可以访问Building中私有成员
	Building* builidng;	
};
class Building
{
	//告诉编译器 GoodGay类中的visit成员函数作为本类的好朋友,可以访问私有函数
	friend void GoodGay::visit();
public:
	Building(); 
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};


void GoodGay::visit()
{
	cout << "visit正在访问" << builidng->m_SittingRoom << endl;
	cout << "visit正在访问" << builidng->m_BedRoom << endl;
}
void GoodGay::visit1()
{
	cout << "visit1正在访问" << builidng->m_SittingRoom << endl;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值