繁体   English   中英

无法从朋友 function 访问 class 的私有成员? 'ostream' 不是'std' 的成员?

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

所以我在我写的 header 文件中为复数和重载 << 运算符编写了 class

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;
}

它告诉我,我无法访问 class 的私有成员,尽管我将其声明为朋友 function。 另外,我得到这个错误“'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";
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM