无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
Can't access a private member of a class from a friend function? 'ostream' is not a member of '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' 的成员"。 我能做些什么呢?
如果没有完整的最小工作示例,很难说出导致错误的原因。一个可能的错误是好友声明的签名与定义不同。
这是一个工作示例:
#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";
...
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数
- 静态与成员运算符重载:标准::运算符<< 和 std::ostream::运算符<<
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- ostream << 具有模板类的操作员,无法访问私有成员
- 派生成员和重载Ostream运算符
- 我的 ostream 和 istream 好友函数无法访问私有类成员
- 使用std::ostream作为类成员