c++ - 全局函数与类方法之间的c ++运算符重载区别
问题描述
我有 Java 背景并尝试学习 C++。我有如下所示的代码。我试图了解什么时候应该像这样重载运算符complex operator+(const complex& c2)
,什么时候应该像这样重载运算符complex operator+(complex a, complex b)
。我不能同时拥有这两个函数,因为编译器抱怨歧义,所以我已经注释掉了一个。两个函数(前者是类的方法)产生相同的结果:
#include <iostream>
using namespace std;
//This class is in global scope
class complex {
private:
double re, im;
public:
complex(double r, double i): re {r}, im {i} {}
double real() const {
return re;
}
void real(double r) {
re = r;
}
double imag() const {
return im;
}
void imag(double i) {
im = i;
}
/*
complex operator+(const complex& c2) {
cout << "Single arg operator+\n";
complex c = complex(0, 0);
c.real(re + c2.real());
c.imag(im + c2.imag());
return c;
}
*/
complex& operator+=(const complex& c2) {
cout << "operator+=\n";
re += c2.real();
im += c2.imag();
return *this;
}
void print() {
cout << "Real: " << re << ", Imaginary: " << im << "\n";
}
};
//This function is in global scope
complex operator+(complex a, complex b) {
cout << "Double arg operator+\n";
return a += b;
}
int main() {
complex c = complex(2, 3);
complex c2 = complex(2, 3);
complex c3 = c + c2;
c.print();
c += c2;
c.print();
}
解决方案
推荐阅读
- r - 使用 proj4string(move.ind) 处理移动对象时的警告消息:CRS 对象有注释,在输出中丢失
- python - y/n 在 python 代码中不能正常工作,我不确定为什么
- c++ - 从用户获取输入并将其插入单链表时,我们如何简化和排序多项式
- charts - 仅将数据标签添加到折线图上的最后一个点
- arrays - $in 查询数组字段 Mongo db
- python - 时间序列的一维 CNN 问题
- javascript - Vuejs如何触发外部脚本事件
- vue.js - 如何在 nuxtJs 配置文件的 head 标签中添加包含函数的脚本?
- r - 如何使用 R 4.1 中的 Octave?
- reactjs - 设置 react formik 验证后没有错误消息