运算符重载

运算符重载可以将改变本来运算符的数据类型
有两种形式:重载为类的友元函数或成员函数
1.重载为友元函数:
friend type operator 运算符( )

#include <bits/stdc++.h>
using namespace std;
class Complex {
	public:
		Complex() {real = 0, imag = 0;}
		Complex(double r, double i) {real = r, imag = i;}
		void display();
		friend Complex operator + (Complex c1, Complex c2);
	private:
		double real;
		double imag;
};
void Complex::display() {
	cout << "(" << real << "," << imag << "i"<< ")" <<endl;
}
Complex operator + (Complex c1, Complex c2) {
	return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main () {
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;
	cout << "c1 = "; c1.display();
	cout << "c2 = "; c2.display();
	cout << "c1 + c2 = "; c3.display();
	return 0;
	}

2.重载为类的成员函数
type operator 运算符( )
参数表中的参数数目是重载运算符的操作数-1,如果是双目运算符,左操作数是当前对象本身的数据,右操作数为参数表中的操作数

#include <bits/stdc++.h>
using namespace std;
class Complex {
	public:
		Complex() {real = 0, imag = 0;}
		Complex(double r, double i) {real = r, imag = i;}
		Complex operator + (Complex c2);
		void display();
	private:
		double real;
		double imag;
};
Complex Complex :: operator +(Complex c2) {
	return Complex(real + c2.real, imag + c2.imag); 
}
void Complex::display() {
	cout << "(" << real << "," << imag << "i"<< ")" <<endl;
}
int main () {
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;
	cout << "c1 = "; c1.display();
	cout << "c2 = "; c2.display();
	cout << "c1 + c2 = "; c3.display();
	return 0;
	}

本文作者:misasteria

本文链接:https://www.cnblogs.com/misasteria/p/16182897.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   misasteria  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起