我遇到了一个问题,即使我声明了它,我也无法使用运算符重载。 我有一个复杂数字的CKomplex类:
typedef double number;
class CKomplex
{
private: // member variables
number mReal;
number mImag;
public:
CKomplex(number real = 0);
CKomplex(number real, number imag);
CKomplex(number radius, number phi, bool isRad);
// Operator
void operator+=(CKomplex &rhs);
void operator-=(CKomplex &rhs);
void operator*=(CKomplex &rhs);
void operator/=(CKomplex &rhs);
void operator=(CKomplex &rhs); // =
friend CKomplex operator+(CKomplex &lhs, CKomplex &rhs); // +
friend CKomplex operator-(CKomplex &lhs, CKomplex &rhs);
friend CKomplex operator*(CKomplex &lhs, CKomplex &rhs);
friend CKomplex operator/(CKomplex &lhs, CKomplex &rhs);
// Get & Setter
number GetReal() { return mReal; }
void SetReal(number real) { mReal = real; }
number GetImag() { return mImag; }
void SetImag(number imag) { mImag = imag; }
}
// Here is the implementation
void CKomplex::operator=(CKomplex &rhs) { // no friend
mReal = rhs.GetReal();
mImag = rhs.GetImag();
}
CKomplex operator+(CKomplex &lhs, CKomplex &rhs) { // friend
number real = lhs.GetReal() + rhs.GetReal();
number imag = lhs.GetImag() + rhs.GetImag();
return CKomplex(real, imag);
}
但是当我在main()函数中编写代码时代码不会编译:
CKomplex z1 = CKomplex(5,3); // works
CKomplex z2 = CKomplex(8,5); // works
CKomplex z3 = z1 + z3; // works; but why?
z3 = z1; // works
z3 = z1 + z2; // doesnt work line 30
z3 = (z1 + z2); // doesnt work also
错误:
C:\Users\User\Documents\soExample\main.cpp:30: Fehler: no match for 'operator=' (operand types are 'CKomplex' and 'CKomplex')
z3 = z1 + z2;
^
(在=处的箭头)
它是我的第一个C ++程序,我在Windows 7上使用QT 5.6.0作为控制台应用程序。
如果您需要进一步的信息,我也可以给您完整的源代码 为什么第3行在main()中编译但不在第6行编译?运营商的区别在哪里?