我正在尝试为一个类重载一个运算符:
#include <iostream>
using namespace std;
class Complex{
float re, im;
public:
Complex(float x = 0, float y = 0) : re(x), im(y) { }
friend Complex operator*(float k, Complex c);
};
Complex operator*(float k, Complex c) {
Complex prod;
prod.re = k * re; // Compile Error: 're' was not declared in this scope
prod.im = k * im; // Compile Error: 'im' was not declared in this scope
return prod;
}
int main() {
Complex c1(1,2);
c1 = 5 * c1;
return 0;
}
但是朋友功能无权访问私人数据。当我添加对象名称时,错误已解决:
Complex operator*(float k, Complex c) {
Complex prod;
prod.re = k * c.re; // Now it is ok
prod.im = k * c.im; // Now it is ok
return prod;
}
但是根据我正在阅读的注释,第一个代码应该可以正常工作。如何在不添加对象名称(re
而不是c.re
)的情况下修复错误?