C++(运算符重载+)

1.加号运算符重载

  • 实现自定义数据类型的加运算

#include <iostream>
using namespace std;


class Person {
public:
	int m_A, m_B;

	//1.成员函数重载+号
	Person operator+(const Person &p) {
		Person temp;
		temp.m_A = this->m_A + p.m_A;
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}

};

//2.全局运算符重载
//Person operator+(const Person &p1, const Person &p2) {
//	Person temp;
//	temp.m_A = p1.m_A + p2.m_A;
//	temp.m_B = p1.m_B + p2.m_B;
//	return temp;
//}

//3.运算符也可以发生函数重载
Person operator+(const Person &p, int num) {
	Person temp;
	temp.m_A = p.m_A + num;
	temp.m_B = p.m_B + num;
	return temp;
}

//4.测试函数
void test()
{
	Person p1, p2;
	p1.m_A = 10;
	p1.m_B = 10;

	p2.m_A = 20;
	p2.m_B = 20;

	//成员函数方式
	Person p3 = p2 + p1; //相当于p3=p2.operator+(p1)
	cout << "p3.mA: " << p3.m_A << "p3.m_B " << p3.m_B << endl;

	//运算符函数重载
	Person p4 = p3 + 10; //相当于p4=p3.operator+(num)
	cout << "p4.mA: " << p4.m_A << "p4.m_B " << p4.m_B << endl;
}
int main()
{
	test();
    std::cout << "Hello World!\n";
}

总结

  • 1,对于内置数据类型的表达式的运算符是不可能改变的
  • 2,不要滥用运算符重载
posted @ 2021-01-19 11:12  flyingswallow  阅读(216)  评论(0编辑  收藏  举报