c++中重载操作符

1、为什么需要重载操作符?

c++中操作符包括==,>=, >>, << 等。比如==,c++中默认实现比较两个大小是否相等,但当要比较两个class变量是否相等,就要重载操作符==。例如:两个Person类的变量,只有当其age和sex一样时才是同一个人,这时候就需要重载操作符。

2、如何使用操作符?

operator是c++的关键字,要和运算符一起使用。应当把operator==看作一个整体

2.1、类成员函数实现操作符重载

Person.h

#pragma once
#include <string>
using namespace std;
class Person
{
public:
	Person();
	~Person();
	int age;                 //年龄
	string sex;              //性别
	Person(int a,string b);  //构造函数

	bool operator==(Person p2) const;   //比较两个人是否一样
};

Person.cpp

#include "Person.h"

Person::Person(){}
Person::~Person(){}

Person::Person(int a, string b)
{
	this->age = a;
	this->sex = b;
	
}

bool Person::operator==(Person p2) const       //操作符重载
{
	if (this->age == p2.age && this->sex == p2.sex)
	{
		return true;
	}
	return false;
}

main.cpp

#include "Person.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
	Person p1(10, "boy");
	Person p2(10, "boy");
	if (p1 == p2)
		cout << "p1和p2年龄相同" << endl;
	else
		cout << "p1和p2年龄不相同" << endl;
}

注意:p1==p2表示的是p1调用成员函数==,传入的参数为p2。

2.2、全局函数实现操作符重载

注意:对于全局重载操作符,代表左操作数的参数必须被显式指定

main.cpp

class Person
{
	public:
		 int age;
		 string sex;
		 Person(int a, string b)
		 {
			 this->age = a;
			 this->sex = b;
		 }
		 
 };

bool operator==(Person p1, Person p2) //满足要求,做操作数的类型被显示指定
{
	if(p1.age == p2.age && p1.sex == p2.sex)
		return true;
	return false;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值