ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++之运算符重载

2022-08-15 23:00:42  阅读:170  来源: 互联网

标签:p2 temp int C++ 运算符 Person 重载


1 运算符重载

运算符    +    -    *    /    ++    --    %    &&    ->    >    < 等
image

class Person{

public :
	Person(){}
	Person(int a ,int b):m_A(a),m_B(b){}

	/*Person operator+(Person &p){
		Person temp;
		temp.m_A = this->m_A + p.m_A ;
		temp.m_B = this->m_B + p.m_B ;
		return temp;
	}*/

	int m_A;
	int m_B;
};
// 利用全局函数 进行+号运算符的重载
Person operator+(Person &p1, Person &p2) // 二元的运算符重载
{
	Person temp;
	temp.m_A = p1.m_A + p2.m_A;
	temp.m_B = p1.m_B + p2.m_B;
	return temp;
}
void test01(){
	Person p1(10,10);
	Person p2(15,24);
	Person p3 = p1+p2;
	cout << "p3的m_A和p3的m_B" << p3.m_A <<"    "<< p3.m_B << endl;
}

2 左移运算符符号重载

不要滥用运算符重载。重载左移运算符不能写在类里,不能作为成员函数。
cout << p1;
因为是cout调用的,不是其他对象调用的。

#include <iostream>
using namespace std; 

class Person{
public :
	Person(){}

	Person(int a , int b){
		this ->m_A = a;
		this -> m_B = b;
	}

	/*void operator<<(){   // 重载左移运算符不能写到成员函数中

	}*/
	int m_A;
	int m_B;
};

ostream & operator<<(ostream & cout,Person & p)
{	// 第1个参数cout ,第2个参数p1
	cout << p.m_A <<  p.m_B ;
	return cout ;
}

void test01(){
	Person p1(10,10);
	 /*cout << p1.m_A << "&" << p1.m_B <<endl;*/
	// 现在要求是直接使用左移运算符输出p1
	// cout << p1 << endl; // 需要重载左移运算符
	cout << p1 << endl;
}

标签:p2,temp,int,C++,运算符,Person,重载
来源: https://www.cnblogs.com/lofly/p/16589987.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有