类和对象-C++运算符重载-加号运算符重载

news/2024/7/8 12:04:27 标签: c++, 开发语言

加号运算符重载

1、成员函数重载+号

#include<iostream>
	
using namespace std;

class Person
{
public:
	//1、成员函数重载+号
	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;	
}; 

void test01()
{
	Person p1;
	p1.m_A=10;
	p1.m_B=10;
	Person p2;
	p2.m_A=10;
	p2.m_B=10;
	Person p3=p1+p2;
	cout<<"p3.m_A= "<<p3.m_A<<endl;
	cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
    test01();
    return 0;
}

2、全局函数重载+号

#include<iostream>
	
using namespace std;

class Person
{
public:
	
	int m_A;
	int m_B;	
}; 
//2、全局函数重载+号
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;
	p1.m_A=10;
	p1.m_B=10;
	Person p2;
	p2.m_A=10;
	p2.m_B=10;
	Person p3=p1+p2;
	cout<<"p3.m_A= "<<p3.m_A<<endl;
	cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
    test01();
    return 0;
}

3、运算符重载,也可以发生函数重载

#include<iostream>
	
using namespace std;

class Person
{
public:
	
	int m_A;
	int m_B;	
}; 
//2、全局函数重载+号
Person operator+(Person &p1,int num)
{
	Person temp;
	temp.m_A=p1.m_A+num;
	temp.m_B=p1.m_B+num;
	return temp;
} 
void test01()
{
	Person p1;
	p1.m_A=10;
	p1.m_B=10;
	
	Person p3=p1+20;
	cout<<"p3.m_A= "<<p3.m_A<<endl;
	cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
    test01();
    return 0;
}

http://www.niftyadmin.cn/n/5537184.html

相关文章

【数据集】中国农田栅格数据CACD(1986-2021)

中国农田栅格数据(1986-2021) 数据概述数据下载参考精确、详细和及时的耕地范围信息对于保障食品安全和环境可持续性至关重要。然而,由于农业景观的复杂性以及缺乏足够的训练样本,要在大范围地理区域内高空间和时间分辨率下监测耕地动态仍然具有挑战性,特别是对于农业土地…

自动化革新者:PlugLink在“智创设计”中的实战应用

PlugLink&#xff1a;小微企业运营自动化的新引擎 在当今竞争激烈的市场环境下&#xff0c;小微企业要想脱颖而出&#xff0c;除了要有敏锐的市场洞察力&#xff0c;还需具备高效灵活的运营能力。本文将通过一个生动的实例&#xff0c;揭示开源项目PlugLink如何助力一家名为“…

Selenium 等待

环境&#xff1a; Python 3.8 selenium3.141.0 urllib31.26.19 Chromium 109.0.5405.0 &#xff08;32 位&#xff09; # 1 固定等待&#xff08;time&#xff09; # 固定待是利用python语言自带的time库中的sleep()方法&#xff0c;固定等待几秒。 # 这种方式会导致这个脚本运…

nginx配置stream代理

项目中遇到某些服务在内网&#xff0c;需要外网访问的情况&#xff0c;需要配置代理访问。可用nginx搭建代理服务。 TCP代理 通过nginx的stream模块可以直接代理TCP服务&#xff0c;步骤如下&#xff1a; 在/etc/nginx/下新建proxy文件夹&#xff0c;用于存放代理配置。此处…

代码技巧专题 -- 使用策略模式编写HandleService

一.前言 最近项目有实习的同事加入&#xff0c;很多实习同事反映&#xff0c;看不懂项目中的一些使用了设计模式的代码&#xff0c;比如HandleService&#xff0c;Chains&#xff0c;Listener等。本篇就介绍一下策略模式在项目中的使用&#xff0c;也就是我们常在项目中看到的X…

【python】使用conda管理python项目:conda管理不同项目环境,pip下载最新的包

文章目录 一. python包管理概述1. miniforge、Miniconda与Anaconda2. conda与pip的区别是什么&#xff1f;3. pip与conda配合使用 二. 使用conda管理不同py环境1. 创建一个环境2. 解决冲突 三. 命令合集1. conda1.1. 常用1.2. 环境管理1.3. conda分享环境与pip生成requirements…

基于单片机技术的按键扫描电路分析

摘 要&#xff1a; 单片机应用技术被广泛应用于各种智能控制系统中&#xff0c;是电子信息类专业学生必修的一门专业课。在单片机端口信息输入模块中&#xff0c;按键是主要元器件之一&#xff0c;笔者主要介绍矩阵键盘的电路设计及控制程序编写&#xff0c;分析了单片机端口连…

Static关键字的用法详解

Static关键字的用法详解 1、Static修饰内部类2、Static修饰方法3、Static修饰变量4、Static修饰代码块5、总结 &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 在Java编程语言中&#xff0c;static是一个关键字&#xff0c;它可以用于多种上…