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;
}
相关推荐
代码不停几秒前
Java二叉树题目练习
java·开发语言·数据结构
77tian14 分钟前
VMware中快速安装与优化Ubuntu全攻略
开发语言·ubuntu
愚润求学1 小时前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
珊瑚里的鱼1 小时前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
晚秋大魔王1 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——wget
java·linux·运维·开发语言·华为·harmonyos
heath ceTide1 小时前
轻量、优雅、高扩展的事件驱动框架——Hibiscus-Signal
java·开发语言
_extraordinary_1 小时前
Java 常用的Arrays函数
java·开发语言
_extraordinary_1 小时前
Java 类和对象
java·开发语言
Aliano2171 小时前
TestNGException ClassCastException SAXParserFactoryImpl是Java自带的Xerces解析器——解决办法
java·开发语言·python
共享家95271 小时前
哈希的原理、实现
c++·算法