C++友元函数和友元类实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88622039

一 友元函数的例子

1 代码

#include <iostream>
using namespace std;
    
class CRectangle {
    int width, height;
public:
    void set_values(int, int);
    int area(void) {return (width * height);}
    // duplicate是CRectangle的friend
    friend CRectangle duplicate(CRectangle);
};
    
void CRectangle::set_values(int a, int b) {
    width = a;
    height = b;
}
// 在duplicate函数之内,可以访问CRectangle类型的各个对象的成员width和height 
CRectangle duplicate(CRectangle rectparam) {
    CRectangle rectres;
    rectres.width = rectparam.width * 2;
    rectres.height = rectparam.height * 2;
    return (rectres);
}
    
int main() {
    CRectangle rect, rectb;
    rect.set_values(2, 3);
    rectb = duplicate(rect);
    cout << rectb.area() << endl;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
24

二 友员类的例子

1 代码

#include <iostream>
using namespace std;
// 声明函数原型,这是必需的,因为在CRectangle的声明中,我们引用了CSquare。
// CSquare的定义在CRectangle的后面,如果没有该声明,它在CRectangle将不可见
class CSquare;

class CRectangle {
    int width, height;
public:
    int area(void) {return (width * height);}
    void convert(CSquare a);
};
    
class CSquare {
private:
    int side;
public:
    void set_side(int a){side = a; }
    // CRectangle是CSquare的friend
    friend class CRectangle;
};
// CRectangle可以访问CSquare的protect和private成员,更具体地说
// 可以访问CSquare::side
// 友元关系并不是相互的,CSquare不能访问CRectangle中的protect和private成员
void CRectangle::convert(CSquare a) {
    width = a.side;
    height = a.side;
}
    
int main() {
    CSquare sqr;
    CRectangle rect;
    sqr.set_side(4);
    rect.convert(sqr);
    cout << rect.area()<<endl;
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
16

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/88622039