读书人

友元函数必须是public类型吗?解决思路

发布时间: 2012-03-26 15:46:55 作者: rapoo

友元函数必须是public类型吗?

C/C++ code
#include <iostream>using namespace std;class B{private:    void fun(){};};class A{public:    friend void B::fun(){};};int main(){    return 0;}



这段代码Cfree报错[Error] E:\C++\test\main.cpp:28: error: `void B::fun()' is private


C/C++ code
#include <iostream>#include <vector>using namespace std;class A;class B{public:    void fun()    {cout<<A::a<<endl;}};class A{public:    friend void B::fun();private:    int a;};void Test::fun(){    cout<<""<<endl;}int main(){    B b;}

这段[Error] E:\C++\test\main.cpp:9: error: incomplete type `A' used in nested name specifier
[Error] E:\C++\test\main.cpp:20: error: `Test' has not been declared
怎么才能将一个类的函数指定为令一个类的友元函数

[解决办法]
当然需要是public否则 外部怎么可能使用这个成员函数呢?class A对于class B来说就属于外部了。

读书人网 >C++

热点推荐