【问题标题】:Can't access a private member of a class from a friend function? 'ostream' is not a member of 'std'?无法从朋友函数访问类的私有成员? 'ostream' 不是'std' 的成员?
【发布时间】:2020-09-06 09:05:57
【问题描述】:

所以我正在为复数编写一个类,并在我编写的头文件中重载

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 &lt;ostream&gt; 还是#include &lt;iostream&gt;?此外,您的第二个参数应该是对 const 的引用。
  • 好的,现在它没有给我关于“ostream”的错误,但它仍然不允许我访问类的成员。
  • 在定义 operator&lt;&lt;() 之前,编译器需要对类定义和 std::ostream 都有可见性(例如,通过包含适当的标头)。这通常意味着需要在定义(实现)该函数之前包含具有类定义和&lt;iostream&gt; 的标头。编译器不会尝试推断它看不到的定义。

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


【解决方案1】:

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

这是一个工作示例:

#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";
...

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多