C++学习Day05之指针运算符重载


一、程序及输出

1.1 重载->运算符

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Person
{
public:
	Person(int age)
	{	
		cout << "Person的有参构造调用" << endl;
		this->m_Age = age;
	}

	void showAge()
	{
		cout << "年龄为: "<< this->m_Age << endl;
	}

	~Person()
	{
		cout << "Person的析构调用" << endl;
	}

	int m_Age;
};

class SmartPoint
{
public:
	SmartPoint(Person * person)
	{
		this->m_person = person;
	}

	//重载->运算符
	Person * operator->()
	{
		return this->m_person;
	}
	~SmartPoint()
	{
		if (this->m_person)
		{
			delete this->m_person;
			this->m_person = NULL;
		}
	}
private:
	Person * m_person;
};

void test01()
{
	//利用智能指针 管理 new出来的person的释放操作
	SmartPoint sp(new Person(18));
	sp->showAge(); // 本质sp->->showAge(); 编译器简化为 sp->showAge();
}

int main(){
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

输出:
在这里插入图片描述

1.2 重载 * 运算符

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Person
{
public:
	Person(int age)
	{	
		cout << "Person的有参构造调用" << endl;
		this->m_Age = age;
	}

	void showAge()
	{
		cout << "年龄为: "<< this->m_Age << endl;
	}

	~Person()
	{
		cout << "Person的析构调用" << endl;
	}

	int m_Age;
};

class SmartPoint
{
public:
	SmartPoint(Person * person)
	{
		this->m_person = person;
	}
	
	//重载 * 运算符
	Person& operator*()
	{
		return *m_person;
	}
	~SmartPoint()
	{
		if (this->m_person)
		{
			delete this->m_person;
			this->m_person = NULL;
		}
	}
private:
	Person * m_person;
};

void test01()
{
	//利用智能指针 管理 new出来的person的释放操作
	SmartPoint sp(new Person(18));
	(*sp).showAge();
}

int main(){
	test01();
	system("pause");
	return EXIT_SUCCESS;
}

输出:
在这里插入图片描述


二、分析与总结

在 C++ 中,我们可以重载 * 和 -> 运算符来实现自定义类型的解引用和成员访问操作。

* 运算符重载
*运算符可以被重载为类的成员函数或全局函数。
解引用运算符 * 的重载函数通常返回一个引用,以便对对象进行解引用操作。
在重载函数内部,可以实现自定义类型对象的解引用操作,返回解引用后的值。
重载的 * 运算符函数将在解引用操作时被调用。
-> 运算符重载
-> 运算符通常用于访问类的成员变量或成员函数。
-> 运算符的重载函数应该返回一个指向类对象的指针或一个类对象的引用。
在重载函数内部,可以实现对类对象的成员访问,并返回一个指向对象的指针或对象的引用。
重载的 -> 运算符函数将在使用箭头运算符时被调用。
使用 * 和 -> 运算符
通过重载 * 和 -> 运算符,我们可以使自定义类型的对象能够像指针一样进行解引用和成员访问。
使用 * 运算符可以对对象进行解引用操作,获取对象的值。
使用 -> 运算符可以访问对象的成员变量或成员函数。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值