友元函数必须是public类型吗?如何才能将一个类的函数指定为令一个类的友元函数
友元函数必须是public类型吗?怎么才能将一个类的函数指定为令一个类的友元函数
这段代码Cfree报错[Error] E:\C++\test\main.cpp:28: error: `void B::fun()' is private
这段[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
怎么才能将一个类的函数指定为令一个类的友元函数
------解决方案--------------------
使用友元时,要注意声明与定义的依赖关系。
class B
{
public:
void fun() ; //先别定义。只声明。
};
class A
{
public:
friend void B::fun(); //将函数声明为友元。
private:
int a;
};
void B::fun(){ // 然后才定义B::fun()
A aa;
cout<<aa.a<<endl;
}
- 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
怎么才能将一个类的函数指定为令一个类的友元函数
------解决方案--------------------
使用友元时,要注意声明与定义的依赖关系。
class B
{
public:
void fun() ; //先别定义。只声明。
};
class A
{
public:
friend void B::fun(); //将函数声明为友元。
private:
int a;
};
void B::fun(){ // 然后才定义B::fun()
A aa;
cout<<aa.a<<endl;
}