有班级好友但无法访问私有成员
友元函数应该能够访问类的私有成员,对吗? 那么我在这里做错了什么?我已将 .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;
}
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.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这里......
你需要
(我已经被这个问题咬了很多次了;你的运算符重载的定义与声明不太匹配,所以它被认为是一个不同的函数。)
In here...
you need
(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.)
签名不匹配。您的非会员功能很有趣& fun,朋友声明为 const fun&乐趣。
The signatures don't match. Your non-member function takes fun& fun, the friend declared on takes const fun& fun.
您可以通过在类定义中编写友元函数定义来避免此类错误:
缺点是每次对
operator<<
的调用都是内联的,这可能会导致代码膨胀。(另请注意,该参数不能称为
fun
,因为该名称已经表示一种类型。)You can avoid these kinds of errors by writing the friend function definition inside the class definition:
The downside is that every call to
operator<<
is inlined, which might lead to code bloat.(Also note that the parameter cannot be called
fun
because that name already denotes a type.)