所以我正在写一个复数类,用于重载<<运算符,在头文件中我写道
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";
...