標籤:
c friend -- 友元
友元用於突破protected 或者 private 保護的限制,首先要做的是在被訪問者的類中聲明是友元函數或者友元類。代碼如下
- #include <iostream>
- using namespace std;
- class Square{
- private:
- int side;
- public:
- Square(int a):side(a){}
- friend class Rectangle ; //declare the Class is friend
- };
- class Rectangle {
- private:
- int width, height;
- public:
- Rectangle(int a, int b):width(a),height(b){}
- void set_values (int a, int b){
- width = a;
- height = b;
- }
- int girth();
- friend int area (Rectangle &); //declare the friend function here
- int get_width(){return width;}
- int get_height(){return height;}
- void conver_from_square(Square &s){
- width = height = s.side; //access so easily
- }
- };
- //implement the function here , access easily ,too
- int area (Rectangle &r){ return ( r.width * r.height); }
- int r_area(Rectangle &r){ return r.get_width() * r.get_height();}
- int Rectangle::girth(){return width + width + height + height; }
- int main () {
- test_sizeof:
- cout << "sizeof: Square " << sizeof(Square)
- << ",\tRectangle " << sizeof(Rectangle) << "\n\n" ;
- test_access:
- Rectangle r(2,3);
- cout << "area:" << area(r) << "\tgirth:" << r.girth() << endl;
- cout << "onather way:area " << r_area(r) << endl;
- Rectangle r1(2,3);
- Square s(5);
- r1.conver_from_square(s);
- cout << "rectangle convering from square , girth is " << r1.girth() << endl;
- return 0;
- }
結果
- sizeof: Square 4, Rectangle 8
- area:6 girth:10
- onather way:area 6
- rectangle convering from square , girth is 20
看函數
如果不是友元函數或類,訪問情況如 r_area()函數,友元函數就可以直接存取成員。但是和成員函數比起來還是要有區別的,看函數girth()
看看size,友元類或者友元函數並不增加類的大小,只是聲明一下。
c friend -- 友元