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;
}
相关推荐
清朝牢弟2 小时前
Ubuntu系统VScode实现opencv(c++)图像像素类型转换和归一化
c++·opencv·ubuntu
黑色的山岗在沉睡2 小时前
P1948 [USACO08JAN] Telephone Lines S
数据结构·c++·算法·图论
奔波霸的伶俐虫3 小时前
jeecg框架@Dict不生效问题
开发语言·python
玖剹3 小时前
Linux文件操作:从C接口到系统调用
linux·服务器·c语言·c++·笔记·ubuntu
YY_TJJ4 小时前
8.4 Java Web(Maven P50-P57)
java·开发语言·maven
ikkkkkkkl5 小时前
LeetCode:15.三数之和&&18.四数之和
c++·算法·leetcode
pusue_the_sun5 小时前
从零开始搞定类与对象(中)
开发语言·c++·学习
咕噜咕噜啦啦5 小时前
Qt按键响应
开发语言·qt
raoxiaoya5 小时前
Golang中的`io.Copy()`使用场景
开发语言·后端·golang
屁股割了还要学5 小时前
【数据结构入门】链表
c语言·开发语言·数据结构·c++·学习·算法·链表