c friend -- 友元

來源:互聯網
上載者:User

標籤:

c friend -- 友元

友元用於突破protected 或者 private 保護的限制,首先要做的是在被訪問者的類中聲明是友元函數或者友元類。代碼如下

  1. #include <iostream>
  2. using namespace std;
  3. class Square{
  4.         private:
  5.                 int side;
  6.         public:
  7.                 Square(int a):side(a){}
  8.         friend class Rectangle ; //declare the Class is friend
  9. };
  10. class Rectangle {
  11.         private:
  12.                 int width, height;
  13.         public:
  14.                 Rectangle(int a, int b):width(a),height(b){}
  15.                 void set_values (int a, int b){
  16.                         width = a;
  17.                         height = b;
  18.                 }
  19.                 int girth();
  20.                 friend int area (Rectangle &); //declare the friend function here
  21.                 int get_width(){return width;}
  22.                 int get_height(){return height;}
  23.                 void conver_from_square(Square &s){
  24.                         width = height = s.side; //access so easily
  25.                 }
  26. };
  27. //implement the function here , access easily ,too
  28. int area (Rectangle &r){ return ( r.width * r.height); }
  29. int r_area(Rectangle &r){ return r.get_width() * r.get_height();}
  30. int Rectangle::girth(){return width + width + height + height; }
  31. int main () {
  32. test_sizeof:
  33.         cout << "sizeof: Square " << sizeof(Square)
  34.              << ",\tRectangle " << sizeof(Rectangle) << "\n\n" ;
  35. test_access:
  36.         Rectangle r(2,3);
  37.         cout << "area:" << area(r) << "\tgirth:" << r.girth() << endl;
  38.         cout << "onather way:area " << r_area(r) << endl;
  39.         Rectangle r1(2,3);
  40.         Square s(5);
  41.         r1.conver_from_square(s);
  42.         cout << "rectangle convering from square , girth is " << r1.girth() << endl;
  43.         return 0;
  44. }
結果
  1. sizeof: Square 4, Rectangle 8
  2. area:6 girth:10
  3. onather way:area 6
  4. rectangle convering from square , girth is 20
看函數
  • area
  • r_area
  • girth
如果不是友元函數或類,訪問情況如 r_area()函數,友元函數就可以直接存取成員。但是和成員函數比起來還是要有區別的,看函數girth() 
看看size,友元類或者友元函數並不增加類的大小,只是聲明一下。

c friend -- 友元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.