运算符重载
运算符重载可以将改变本来运算符的数据类型
有两种形式:重载为类的友元函数或成员函数
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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通