[英]Friend ostream can't access private member
I have seen other questions like this but I didn't get a solution. 我见过这样的其他问题,但我没有得到解决方案。 Here is the code:
这是代码:
cout_overload.h: cout_overload.h:
#ifndef COUT_OVERLOAD_H_
#define COUT_OVERLOAD_H_
#include <iostream>
class A
{
private:
int data;
public:
A(int d);
friend std::ostream & operator <<
(std::ostream os, const A &t );
};
#endif
cout_overload_r.cpp: cout_overload_r.cpp:
#include <iostream>
#include "cout_overload.h"
A::A(int d)
{
data = d;
}
std::ostream &operator << (std::ostream &os, const A&t)
{
os << " t = " << t.data ;
return os;
}
main.cpp: main.cpp中:
#include <iostream> #include "cout_overload.h"
int main(void)
{
A ra(1);
using std::cout;
// cout<<ra;
return 0;
}
You need to modify your friend
function and Use ostream&
inside the 您需要修改您的
friend
功能并使用ostream&
friend std::ostream & operator << (std::ostream os, const A &t );
And replace your above line, 并替换你的上述行,
friend std::ostream & operator << (std::ostream &os, const A &t );
Because ostream
is an output stream, the &
is to pass by reference ( the only way to pass streams to functions ).. 因为
ostream
是一个输出流,所以&
将通过引用传递(将流传递给函数的唯一方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.