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;
}
相关推荐
软件黑马王子3 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫3 小时前
go orm GORM
开发语言·后端·golang
黑不溜秋的4 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学5 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?6 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农6 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿6 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!6 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
柠石榴6 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
王老师青少年编程6 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛