好友ostream无法访问私人会员
Friend ostream can't access private member
我也看到过类似的其他问题,但我没有得到解决方案。
代码如下:
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:
#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:
#include <iostream> #include "cout_overload.h"
int main(void)
{
A ra(1);
using std::cout;
// cout<<ra;
return 0;
}
编译时报错:
您需要修改 friend
函数并在
中使用 ostream&
friend std::ostream & operator << (std::ostream os, const A &t );
并替换上面的行,
friend std::ostream & operator << (std::ostream &os, const A &t );
因为ostream
是一个输出流,所以&
是通过引用传递(将流传递给函数的唯一方法)..
我也看到过类似的其他问题,但我没有得到解决方案。 代码如下:
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:
#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:
#include <iostream> #include "cout_overload.h"
int main(void)
{
A ra(1);
using std::cout;
// cout<<ra;
return 0;
}
编译时报错:
您需要修改 friend
函数并在
ostream&
friend std::ostream & operator << (std::ostream os, const A &t );
并替换上面的行,
friend std::ostream & operator << (std::ostream &os, const A &t );
因为ostream
是一个输出流,所以&
是通过引用传递(将流传递给函数的唯一方法)..