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;
}
相关推荐
攻城狮7号几秒前
Python爬虫第19节-动态渲染页面抓取之Splash使用下篇
开发语言·爬虫·python·python爬虫
天天进步20156 分钟前
Python项目--基于计算机视觉的手势识别控制系统
开发语言·python·计算机视觉
mozun202010 分钟前
QT:Qt5 串口模块 (QSerialPort) 在 VS2015 中正确关闭串口避免被占用
开发语言·c++·qt·串口·串口调试·上位机软件
小刘同学++12 分钟前
Qt 中线程使用
开发语言·qt
徐寿春15 分钟前
规则引擎 - Easy Rules
java·开发语言
byte轻骑兵17 分钟前
【C++ 类和数据抽象】static 类成员
开发语言·c++
努力学习的小廉24 分钟前
【C++】 —— 笔试刷题day_24
开发语言·c++
刃神太酷啦27 分钟前
堆和二叉树--数据结构初阶(3)(C/C++)
c语言·数据结构·c++·算法·leetcode·深度优先·宽度优先
爱的叹息42 分钟前
Java虚拟机(JVM)家族发展史及版本对比
java·开发语言·jvm
用户jjbjjbk1 小时前
QT多线程以及事件循环
c++·qt