1.友元函数
可以访问不受public protected private影响。
func.h
#ifndef __FUNC__ #define __FUNC__ #include#include using namespace std; #include "test.h" class Test; void testFuncFriend(const Test &tempmen); #endif // !__FUNC__
func.cpp
#include#include #include "func.h" using namespace std; void testFuncFriend(const Test &temp) { cout << "testFuncFriend" << endl; temp.testFunc(); }
test.h
#ifndef __TEST__ #define __TEST__ #include#include #include "func.h" using namespace std; class Test { public: Test(); private: void testFunc() const{ cout << "test" << endl; } friend void testFuncFriend(const Test &temp); }; #endif // !__Test__
test.cpp
#include#include #include "test.h" using namespace std; Test::Test() { cout << "执行了Test::Test()构造函数" << endl; }
main.cpp
#include#include #include "func.h" #include "test.h" using namespace std; int main() { Test test; testFuncFriend(test); return 0; }
通过在Test中添加friend void testFuncFriend(const Test &temp);就可以在func的testFuncFriend中访问Test中的private(testFunc)方法。
2.友元类与友元成员函数
A.cpp
#include#include using namespace std; #include "A.h"
A.h
#ifndef __A__
#define __A__
#include "C.h"
class A
{
friend void C::cCallA(int x,A &a);//此函数内才能访问A中的成员变量和成员函数
//friend class C;//添加之后 C可以访问A所有的成员变量和成员函数
private:
int data;
};
#endif
c.cpp
#include#include using namespace std; #include "A.h" #include "C.h" void C::cCallA(int x,A &a) { a.data = x; cout << a.data << endl; cout << "cCallA" << endl; }
c.h
#ifndef __C__ #define __C__ #include#include using namespace std; class A; class C { public: void cCallA(int x,A &a); }; #endif // !__C__
main.cpp
#include#include #include "func.h" #include "A.h" #include "C.h" #include "test.h" using namespace std; int main() { A a; C c; c.cCallA(10,a); Test test; testFuncFriend(test); return 0; }
结果为:
10
cCallA
执行了Test::Test()构造函数
testFuncFriend
test
通过在A中添加friend void C::cCallA(int x,A &a);就可以访问A中的私有变量。



