您的位置:首页 > 其它

Friend function should be a public function, if it is in a class.

2011-11-04 11:39 495 查看
See the code please.

JSC.h

#ifndef JSC_H_
#define JSC_H_

#include <iostream>
using namespace std;

class JYJ;
class JSC
{
public:
JSC() {}
//private:
void look(const JYJ& jyj);
};

#include "JYJ.h"

void JSC::look(const JYJ& jyj)
{
cout<<jyj.blove<<endl;
}
#endif /* JSC_H_ */


JYJ.h

#ifndef JYJ_H_
#define JYJ_H_

#include "JSC.h"

class JYJ
{
public:
JYJ() { blove = true; }
friend void JSC::look(const JYJ& jyj);
private:
bool blove;
};

#endif /* JYJ_H_ */


main.cpp

#include "JSC.h"
#include "JYJ.h"

int main()
{
JSC jsc;
JYJ jyj;
jsc.look(jyj);
return 0;
}




How about changing the friend function to a private member? See the result!

JSC.h

#ifndef JSC_H_
#define JSC_H_

#include <iostream>
using namespace std;

class JYJ;
class JSC
{
public:
JSC() {}
private:
void look(const JYJ& jyj);
};

#include "JYJ.h"

void JSC::look(const JYJ& jyj)
{
cout<<jyj.blove<<endl;
}
#endif /* JSC_H_ */




It is clear to see the error. It is the same with "protected", only right in "public". Also, it is interesting to note the " #include " and " class " sequence in the coding.

Thanks to the comment. I should take your illustration to rephrase this issue. Yes, :: only decides the attribution to whom, whereas in order to let the class JYJ see the friend function, the one should be public only.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐