1.friend 关键字 类外部的函数得到可以直接访问 类内部私或保护成员的权限

2.以下有三种友员函数实现方式

//外部函数访问一个类私有数据

//外部函数访问两个类私有数据

//类的成员函数 访问 其它类的私有函数



friend.h 头文件

  1. #ifndef FREIND_H 
  2. #define FREIND_H 
  3.  
  4. #include<iostream> 
  5. #include<string> 
  6. using namespace std; 
  7.  
  8. class A; 
  9. class B; 
  10. void display(A&); 
  11. void display(A&, B&); 
  12.  
  13.  
  14. class A 
  15. public: 
  16.       A(string &);   
  17.     friend void display(A&); //外部函数访问一个类私有数据
  18.     void display(B&); //类的成员函数 访问 其它类的私有函数
  19.     friend void display(A&, B&);//外部函数访问两个类私有数据 
  20.      
  21. private: 
  22.     string str; 
  23. }; 
  24.  
  25. class B 
  26. public: 
  27.       B(string&); 
  28.       friend void A::display(B&); 
  29.       friend void display(A&, B&);   
  30. private: 
  31.     string str; 
  32. }; 
  33.  
  34.  
  35.  
  36.  
  37. #endif // end FREIND_H 

 


friend.cpp 实现文件

  1. #include"friend.h" 
  2. #include<iostream> 
  3. using namespace std; 
  4.  
  5. void display(A& test) 
  6.       cout<<"void display(A& test)"<<endl
  7.       cout<<test.str<<endl
  8.  
  9. void display(A& a, B& b) 
  10.       cout<<"void display(A& a, B& b)"<<endl
  11.       cout<<a.str<<endl
  12.       cout<<b.str<<endl
  13.  
  14. //------------------------------------------------- 
  15.  
  16. A::A(string& s):str(s){} 
  17. void A::display(B& test) 
  18.       cout<<"void A::display(B& test)"<<endl
  19.       cout<<this->str<<endl
  20.       cout<<test.str<<endl
  21.  
  22. //------------------------------------------------- 
  23.  
  24. B::B(string& s):str(s){} 

 


main.cpp主程序文件


  1. #include<iostream> 
  2. #include"friend.h" 
  3.  
  4. using namespace std; 
  5.  
  6. int main() 
  7.       string str0 = "this class A"
  8.       string str1 = "this class B"
  9.        
  10.       A a(str0);  
  11.       B b(str1);          
  12.        
  13.       display(a); 
  14.       a.display(b);   
  15.       display(a,b);            
  16.              
  17.       return 0; 

 


makefile文件

  1. srcs=$(wildcard *.c) 
  2. objs =$(patsubst %c,%o,$(srcs)) 
  3. CC = gcc 
  4. Target = main 
  5.  
  6. #################### 
  7.  
  8. .PHONY: all clean # command: make all or make clean 
  9.  
  10. clean:  
  11.     rm -f $(obj) main *~ *gch 
  12.      
  13.      
  14. ################### 
  15. all: $(Target) 
  16.  
  17. $(Target):$(objs) 
  18.     $(CC) -o $@ $^ 
  19. main.o:main.c  
  20.     $(CC) -c $< 
  21. tool0.o:tool0.c  
  22.     $(CC) -c $< 
  23. tool1.o:tool1.c  
  24.     $(CC) -c $<