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;
}
相关推荐
Howrun7774 分钟前
C++ 智能指针_详细解释
开发语言
stolentime4 分钟前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco
编程大师哥10 分钟前
JavaScript DOM
开发语言·javascript·ecmascript
dazzle10 分钟前
Python数据结构(四):栈详解
开发语言·数据结构·python
CSDN_RTKLIB13 分钟前
C++多元谓词
c++·算法·stl
毕设源码-邱学长15 分钟前
【开题答辩全过程】以 基于java的办公自动化系统设计为例,包含答辩的问题和答案
java·开发语言
json{shen:"jing"}22 分钟前
10_自定义事件组件交互
开发语言·前端·javascript
一位搞嵌入式的 genius25 分钟前
深入理解 JavaScript 异步编程:从 Event Loop 到 Promise
开发语言·前端·javascript
brevity_souls30 分钟前
SQL Server 窗口函数简介
开发语言·javascript·数据库
火云洞红孩儿40 分钟前
零基础:100个小案例玩转Python软件开发!第六节:英语教学软件
开发语言·python