无法通过好友功能访问班级的私人成员? 'ostream'不是'std'的成员吗?

时间:2020-05-20 05:18:29

标签: c++ class oop operator-overloading std

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

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'的成员”。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

这是一个可行的示例:

#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";
...
相关问题