《C++Primer》读书笔记(9)

本文详细介绍了C++中运算符重载的概念及其应用场景,包括算术运算符、比较运算符和输入输出运算符的重载实现。通过具体实例展示了如何通过重载提高代码的可读性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.运算符重载,当有的时候对象运算与正常运算符的操作意义相同时,为了代码的简洁,我们就可以使用运算符重载。

比如一个简单的加法操作,没有必要再写一个add方法,还是一个+看着比较顺眼。

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

class A
{
private:
	int num;
	string name;
public:
	A(int n){num = n;}
	//一种重载方式,类的成员函数
	A operator+ (A a)
	{
		a.num = this->num + a.num;
		return  a;
	}
	void Display()
	{
		cout<<num<<endl;
	}
	//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量
	friend A operator-(A, A);
};

A operator- (A a, A b)
{
	a.num = a.num - b.num;
	return a;
}

int _tmain(int argc, _TCHAR* argv[])
{
	A a(10);
	A b(11);
	(a + b).Display();

	(a - b).Display();

	getchar();
	return 0;
}


<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">运算符重载可以理解为:</span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);"> a+b  <=>a.operator+(b)</span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">a - b <=> operator-(a, b)</span>


一个重载<<标准输出运算符的例子:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

class A
{
private:
	int num;
public:
	A(int n){num = n;}
	
	//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量
	friend ostream& operator<<(ostream& os, A a);
};

ostream& operator<<(ostream& os, A a)
{
	cout<<a.num;
	return os;
}

int _tmain(int argc, _TCHAR* argv[])
{
	A a(10);
	cout<<a<<endl;
	getchar();
	return 0;
}


重载==和!=运算符的例子:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

class A
{
private:
	int num;
	string name;
public:
	A(int n, string na){num = n;name = na;}
	
	//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量

	//重载==运算符
	friend bool operator==(const A&, const A&);
	//重载!=运算符
	friend bool operator!=(const A&, const A&);
};


bool operator==(const A& a, const A& b)
{
	return a.num == b.num && a.name == b.name;
}

bool operator!=(const A& a, const A& b)
{
	//写好了就该用,开始自己差点重写了一个!=的单独的判断的。果然还是编程不够多啊。
	return !(a==b);
}

int _tmain(int argc, _TCHAR* argv[])
{
	A a(10, "haha");
	A b(10, "haha");
	if (a == b)
		cout<<"a == b"<<endl;
	else
		cout<<"a != b"<<endl;
	getchar();
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值