1.friend 关键字 类外部的函数得到可以直接访问 类内部私或保护成员的权限
2.以下有三种友员函数实现方式
//外部函数访问一个类私有数据
//外部函数访问两个类私有数据
//类的成员函数 访问 其它类的私有函数
friend.h 头文件
- #ifndef FREIND_H
- #define FREIND_H
- #include<iostream>
- #include<string>
- using namespace std;
- class A;
- class B;
- void display(A&);
- void display(A&, B&);
- class A
- {
- public:
- A(string &);
- friend void display(A&); //外部函数访问一个类私有数据
- void display(B&); //类的成员函数 访问 其它类的私有函数
- friend void display(A&, B&);//外部函数访问两个类私有数据
- private:
- string str;
- };
- class B
- {
- public:
- B(string&);
- friend void A::display(B&);
- friend void display(A&, B&);
- private:
- string str;
- };
- #endif // end FREIND_H
friend.cpp 实现文件
- #include"friend.h"
- #include<iostream>
- using namespace std;
- void display(A& test)
- {
- cout<<"void display(A& test)"<<endl;
- cout<<test.str<<endl;
- }
- void display(A& a, B& b)
- {
- cout<<"void display(A& a, B& b)"<<endl;
- cout<<a.str<<endl;
- cout<<b.str<<endl;
- }
- //-------------------------------------------------
- A::A(string& s):str(s){}
- void A::display(B& test)
- {
- cout<<"void A::display(B& test)"<<endl;
- cout<<this->str<<endl;
- cout<<test.str<<endl;
- }
- //-------------------------------------------------
- B::B(string& s):str(s){}
main.cpp主程序文件
- #include<iostream>
- #include"friend.h"
- using namespace std;
- int main()
- {
- string str0 = "this class A";
- string str1 = "this class B";
- A a(str0);
- B b(str1);
- display(a);
- a.display(b);
- display(a,b);
- return 0;
- }
makefile文件
- srcs=$(wildcard *.c)
- objs =$(patsubst %c,%o,$(srcs))
- CC = gcc
- Target = main
- ####################
- .PHONY: all clean # command: make all or make clean
- clean:
- rm -f $(obj) main *~ *gch
- ###################
- all: $(Target)
- $(Target):$(objs)
- $(CC) -o $@ $^
- main.o:main.c
- $(CC) -c $<
- tool0.o:tool0.c
- $(CC) -c $<
- tool1.o:tool1.c
- $(CC) -c $<