[英]friend with class but can't access private members
Friend functions should be able to access a class private members right? 朋友功能应该能够访问类私有成员吗? So what have I done wrong here?
那我在这里做错了什么? I've included my .h file with the operator<< I intent to befriend with the class.
我已经将我的.h文件包含在操作符<<我打算与该类成为朋友。
#include <iostream>
using namespace std;
class fun
{
private:
int a;
int b;
int c;
public:
fun(int a, int b);
void my_swap();
int a_func();
void print();
friend ostream& operator<<(ostream& out, const fun& fun);
};
ostream& operator<<(ostream& out, fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
In here... 在这里...
ostream& operator<<(ostream& out, fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
you need 你需要
ostream& operator<<(ostream& out, const fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
(I've been bitten on the bum by this numerous times; the definition of your operator overload doesn't quite match the declaration, so it is thought to be a different function.) (我已经被这么多次咬了过来;你的运算符重载的定义与声明不完全匹配,所以它被认为是一个不同的函数。)
The signatures don't match. 签名不匹配。 Your non-member function takes fun& fun, the friend declared on takes const fun& fun.
你的非会员功能带来了乐趣和乐趣,这位朋友宣称这将带来趣味和乐趣。
You can avoid these kinds of errors by writing the friend function definition inside the class definition: 您可以通过在类定义中编写友元函数定义来避免这些错误:
class fun
{
//...
friend ostream& operator<<(ostream& out, const fun& f)
{
out << "a= " << f.a << ", b= " << f.b << std::endl;
return out;
}
};
The downside is that every call to operator<<
is inlined, which might lead to code bloat. 缺点是每次调用
operator<<
都会内联,这可能会导致代码膨胀。
(Also note that the parameter cannot be called fun
because that name already denotes a type.) (另请注意,该参数不能称为
fun
因为该名称已经表示类型。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.