標籤:++ 友元 構造 void 析構 std col nbsp str
友元函數可以修改類的私人屬性,寫在類的public/private/protected底下都可以。友元函數的函數體寫在類的外面時,寫法和普通函數一樣,不需要加friend關鍵字,但函數入口參數裡面一般肯定是要帶一個類的指標或者類的引用以便使用類的私人屬性。
友元類的作用和友元函數相同。當一個類A被聲明為另外一個類B的友元類時,則類A可以訪問類B的私人屬性。類A中的函數入口參數一般都要帶有類B的指標或類B的引用。
例如:
1 //.h檔案 2 #pragma once 3 class myteacher 4 { 5 public: 6 myteacher(void);//無參建構函式 7 myteacher::myteacher(int a,const char* n);//有參建構函式 8 myteacher(const myteacher&);//拷貝建構函式 9 ~myteacher(void); 10 void printT(void); 11 friend void modifyT(myteacher&,int,const char*); 12 friend class mystudent;//mystudent是myteacher的友元類,可以訪問myteacher中的私人屬性 13 14 private: 15 int age; 16 char name[32]; 17 }; 18 19 20 class mystudent 21 { 22 public: 23 mystudent(int s); 24 void printT(myteacher&); 25 26 private: 27 int score; 28 }; 29 30 31 32 //.cpp檔案 33 #include "myteacher.h" 34 #include <string.h> 35 #include <iostream> 36 37 //無參建構函式 38 myteacher::myteacher(void) 39 { 40 age=18; 41 strcpy(name,"Li"); 42 } 43 44 //有參建構函式 45 myteacher::myteacher(int a,const char* n) 46 { 47 age=a; 48 strcpy(name,n); 49 } 50 51 //拷貝建構函式 52 myteacher::myteacher(const myteacher& T) 53 { 54 age=T.age; 55 strcpy(name,T.name); 56 } 57 58 //列印函數 59 void myteacher::printT() 60 { 61 std::cout<<age<<std::endl; 62 std::cout<<name<<std::endl; 63 } 64 65 66 //解構函式 67 myteacher::~myteacher(void) 68 { 69 } 70 71 //友元函數 72 void modifyT(myteacher& pT,int Age,const char* pN) 73 { 74 pT.age = Age; 75 strcpy(pT.name ,pN); 76 } 77 78 79 mystudent::mystudent(int s=100) 80 { 81 score=s; 82 } 83 84 void mystudent::printT(myteacher& t) 85 { 86 std::cout<<"age:"<<t.age<<std::endl; 87 std::cout<<"name:"<<t.name<<std::endl; 88 } 89 90 91 //main函數 92 #include<iostream> 93 #include "myteacher.h" 94 95 using namespace std; 96 97 98 int main() 99 {100 myteacher t(25,"Wu");101 t.printT();102 103 modifyT(t,26,"Chen");104 t.printT();105 106 mystudent s(98);107 s.printT(t);108 109 system("pause");110 return 0;111 }
C++中的友元函數和友元類