朋友功能应该能够访问类私有成员吗?那我在这里做错了什么?我已将我的.h文件包含在操作符<<我打算与 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;
}
3 回答
签名不匹配 . 你的非会员功能带来了乐趣和乐趣,这位朋友宣称自己很开心,很有趣 .
您可以通过在类定义中编写友元函数定义来避免这些类型的错误:
缺点是每次调用
operator<<
都会内联,这可能导致代码膨胀 .(另请注意,该参数不能被称为
fun
,因为该名称已经表示类型 . )在这里...
你需要
(我已经被这么多次咬了过来;你的运算符重载的定义与声明不完全匹配,所以它被认为是一个不同的函数 . )