類與友元
阿新 • • 發佈:2019-01-07
1.B中成員函式是A的一個友元函式,主要就是函式定義和類宣告的順序問題
//TVFM.h #ifndef _TVFM_H_ #define _TVFM_H_ #include<iostream> /*B中成員函式是A的一個友元函式,主要就是函式定義和類宣告的順序問題*/ using namespace std; class A;//1.首先前向宣告 class B { private: double b; public: B(double n = 0) :b(n){} ~B(){} void setA(A &obj);//2.如果要利用類A的引用形參,必須加前向宣告 }; class A { private: int a; public: A(int n = 0) :a(n){} ~A(){} void show()const{ cout << "a=" << a << endl; } friend void B::setA(A &obj);//3.宣告為友元 }; inline void B::setA(A &obj)//4.同一個檔案中可以定義為行內函數 { obj.a = (int)b; } #endif //_TVFM_H_ //main.cpp //#include<iostream> //#include<cstdlib> #include"TVFM.h" using namespace std; int main() { A *obja = new A(4); B objb = B(9.5); cout << "The orignal obja:\n"; obja->show(); cout << "After objb.setA(*obja), the obja:\n"; objb.setA(*obja); obja->show(); delete obja; system("pause"); return 0; }
執行結果如下
2./*A和B互為友元函式*/
//TVFM.h #ifndef _TVFM_H_ #define _TVFM_H_ #include<iostream> /*互為友元函式*/ using namespace std; class B { friend class A; private: double b; public: B(double n = 0) :b(n){} ~B(){} void show(){ cout << "b=" << b << endl; } void setA(A &obj); }; class A { friend class B; private: int a; public: A(int n = 0) :a(n){} ~A(){} void show()const{ cout << "a=" << a << endl; } void setB(B &obj); }; inline void A::setB(B &obj) { obj.b = (double)a; } inline void B::setA(A &obj) { obj.a = (int)b; } #endif //_TVFM_H_ //main.cpp //#include<iostream> //#include<cstdlib> #include"TVFM.h" using namespace std; int main() { A *obja = new A(4); B objb = B(9.5); cout << "The orignal obja:\n"; obja->show(); cout << "After objb.setA(*obja), the obja:\n"; objb.setA(*obja); obja->show(); obja->setB(objb); cout << "obja->setB(objb), the objb:\n"; objb.show(); delete obja; system("pause"); return 0; }
程式執行結果如下