【发布时间】:2018-07-11 09:06:39
【问题描述】:
重载运算符+实现以下操作:
- Obj1 + Obj2
- 12 + Obj2
- Obj1 + 10
重载运算符 - 实现以下操作:
- Obj1 - Obj2
- 12 - Obj2
- Obj1 - 10
主要看重载:Obj1-10、12-Obj2、12+Obj2、Obj1+10例 我想重载运算符 + 和 - 以便处理所有操作。如何处理这些操作/案例? 在这里,我面临第二种情况的问题。我正在考虑只为 + 和 - 编写一个函数来处理这些情况。
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator + (Complex const &obj) {
Complex res;
res.real = this->real + obj.real;
res.imag = this->imag + obj.imag;
return res;
}
Complex operator + (int i) {
Complex res;
res.real = this->real + i;
res.imag = this->imag ;
return res;
}
Complex operator - (Complex const &obj) {
Complex res;
res.real = this->real - obj.real;
res.imag = this->imag - obj.imag;
return res;
}
Complex operator - (int i) {
Complex res;
res.real = this->real - i;
res.imag = this->imag ;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex Obj1(10, 5), Obj2(2, 4);
Complex Obj3 = Obj1 + Obj2;
Complex Obj4 = 10 + Obj3;
Complex Obj5 = Obj4 + 15;
cout<<" + operation:"<<endl;
Obj3.print();
Obj4.print();
Obj5.print();
Complex Obj6 = Obj1 - Obj2;
Complex Obj7 = 10 - Obj3;
Complex Obj8 = Obj4 - 15;
cout<<" - operation:"<<endl;
Obj6.print();
Obj7.print();
Obj8.print();
}
预期输出:
+ operation:
12 + i9
22 + i9
37 + i9
- operation:
8 + i
2 + i9
7 + i9
出现以下错误:
error: no match for 'operator+' (operand types are 'int' and 'Complex')
Complex Obj4 = 10 + Obj3;
【问题讨论】:
-
那么.. 你的问题是什么?您到底遇到了什么问题?
-
您可以将运算符重载为成员函数或非成员函数。我建议您get a few good books 阅读所有相关信息。
-
对一个有效问题投了这么多票的原因是什么?
-
OP,Mat 提供的链接有帮助吗?我们认为这可能是一个骗局'
标签: c++ c++11 operator-overloading c++14