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

来源:互联网 发布:nemo阿拉伯语软件 编辑:程序博客网 时间:2024/06/11 13:38

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.

 

原创粉丝点击