【发布时间】:2020-05-24 18:08:53
【问题描述】:
我正在学习 C++ 中的重载运算符,我已经编写了关于两个虚数之和的代码,由实部和虚部组成。
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r, int i) {
real = r;
imag = i;
}
Complex operator + (Complex const &num1, Complex const &num2) {
Complex res;
res.real = num1.real + num2.real;
res.imag = num1.imag + num2.imag;
return res;
}
void print() {
cout << real << " + i" << imag << endl;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
应该有问题,因为它显示了很多错误、注释和警告:(
error: ‘Complex Complex::operator+(const Complex&, const Complex&)’ must take either zero or one argument
error: no match for ‘operator+’ (operand types are ‘Complex’ and ‘Complex’)
note: ‘Complex’ is not derived from ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
【问题讨论】:
-
好的,有哪些错误、注释和警告?
-
你已经像朋友函数一样重载了它们。
-
你在
res.imag = num1.imag + num1.imag;中有一个双重num1.imag -
注意:C++ 已经有std::complex。
标签: c++ class oop object operator-overloading