C++中的友元函數和友元類

來源:互聯網
上載者:User

標籤:++   友元   構造   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++中的友元函數和友元類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.