【发布时间】:2021-05-29 19:52:13
【问题描述】:
我正在尝试为一个类重载一个运算符:
#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)的情况下修复错误?
【问题讨论】:
-
friend函数是免费函数。不是类成员函数,所以没有隐含的this->。 -
c.re是对由于friend而允许的类实例的私有成员访问。您的函数不是成员函数。 -
显然你的笔记不正确
-
是的,要么你的笔记有误,要么你遗漏了什么。
-
您使用额外的
c.所做的更改是正确的解决方案。
标签: c++ private-members friend-function member-access