C++ 面向对象编程:+号运算符重载,左移运算符重载

像+、-号进行运算符重载,过程类似,见以下代码示例:

cpp 复制代码
#include<iostream>
#include<string>
using namespace std;

class number1 {
    friend number1 operator+(number1& one, number1& two);
public:
    number1():msg1(0), msg2(1){}
    number1(int msg1, int msg2) {
        this->msg1 = msg1;
        this->msg2 = msg2;
    }
    void Print() {
        cout << msg1 << "+" << msg2 << endl;
    }
private:
    int msg1;
    int msg2;
};

number1 operator+(number1& one, number1& two) {
    number1 num1;
    num1.msg1 = one.msg1 + two.msg1;
    num1.msg2 = one.msg2 + two.msg2;
    return num1;
}

int main() {
    number1 a(1, 2);
    number1 b(2, 3);
    number1 c = a + b;
    c.Print();
    return 0;
}

左移运算符一般是这种样式:对象为e的话,cout.operator<<(e),成员函数的重载是这样的:

e.opeerator<<(cout),可以作为当前类的成员函数,这样就可以实现对象的输出,见以下代码示例

cpp 复制代码
#include<iostream>
#include<string>
using namespace std;

class number1 {
	friend number1 operator+(number1& one, number1& two);
	friend ostream& operator<<(ostream& cout, number1 a);
public:
	number1():msg1(0), msg2(1){}
	number1(int msg1, int msg2) {
		this->msg1 = msg1;
		this->msg2 = msg2;
	}
	void Print() {
		cout << msg1 << "+" << msg2 << endl;
	}
private:
	int msg1;
	int msg2;
};

number1 operator+(number1& one, number1& two) {
	number1 num1;
	num1.msg1 = one.msg1 + two.msg1;
	num1.msg2 = one.msg2 + two.msg2;
	return num1;
}

ostream& operator<<(ostream& cout, number1 a) {
	cout << a.msg1 << a.msg2 << endl;
	return cout;
}

int main() {
	number1 a(1, 2);
	number1 b(2, 3);
	number1 c = a + b;
	c.Print();
	cout << c << endl;
	return 0;
}
相关推荐
阿里嘎多学长4 分钟前
2026-04-30 GitHub 热点项目精选
开发语言·程序员·github·代码托管
j_xxx404_2 小时前
Linux:静态链接与动态链接深度解析
linux·运维·服务器·c++·人工智能
叶小鸡2 小时前
Java 篇-项目实战-苍穹外卖-笔记汇总
java·开发语言·笔记
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题】【Java基础篇】第22题:HashMap 和 HashSet 有哪些区别
java·开发语言·哈希算法·散列表·hash
c++之路2 小时前
C++23概述
java·c++·c++23
时空系2 小时前
第10篇:继承扩展——面向对象编程进阶 python中文编程
开发语言·python·ai编程
CHANG_THE_WORLD4 小时前
python 批量终止进程exe
开发语言·python
古城小栈4 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
学涯乐码堂主4 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
云栖梦泽5 小时前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++