无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?

Can't access a private member of a class from a friend function? 'ostream' is not a member of 'std'?

本文关键字:成员 ostream 不是 std 好友 访问 功能      更新时间:2023-10-16

所以我正在为复数和重载<<运算符编写一个类,在我编写的头文件中

friend std::ostream& operator<< (std::ostream& out, Complex& a);

我后来在其他文件中定义了

std::ostream& operator<< (std::ostream& out, Complex& a)
{
out << a.real << " + " << a.imaginary << "*i";
return out;
}

它告诉我我无法访问类的私有成员,尽管我将其声明为好友函数。另外,我收到此错误" 'ostream' 不是'std' 的成员"。 我能做些什么呢?

如果没有完整的最小工作示例,很难说出导致错误的原因。一个可能的错误是好友声明的签名与定义不同。

这是一个工作示例:

#include <iostream>
class Complex {
public:
Complex(double re, double im):real(re),imaginary(im){}
// public interface
private:
friend std::ostream& operator<< (std::ostream& out, const Complex& a);
double real = 0;
double imaginary = 0;
};
std::ostream& operator<< (std::ostream& out, const Complex& a)
{
out << a.real << " + " << a.imaginary << "*i";
return out;
}
int main()
{
Complex c(1.,2.);
std::cout << c << std::endl;
}

现在,如果你已经写了

friend std::ostream& operator<< (std::ostream& out, const Complex& a);

但在外面你只有

std::ostream& operator<< (std::ostream& out, Complex& a) // <- const is missing

你将收到编译器警告:

<source>: In function 'std::ostream& operator<<(std::ostream&, Complex&)':
<source>:18:14: error: 'double Complex::real' is private within this context
18 |     out << a.real << " + " << a.imaginary << "*i";
...