正确理解C++的友元friend
C++的友元(friend)是个很重要的概念,该如何正确理解呢?本文将以友元函数为例讲解一下,仔细看。
友元的特性:
1、使用friend修饰的成员函数可以访问其他成员的私有成员(private)和保护成员(protected)。
2、友元不能传递,简单来说就是:她是我的朋友,他是她的朋友,但他不是我的朋友。
友元实例
源代码,仔细看注释内容:
#include <iostream>using namespace std;
/*** 友元函数的定义和使用
*/
class Rectangle{int width, height; //私有成员
public:Rectangle(){} //定义默认构造函数,是一个完整的函数定义,所以行尾不用加分号。去掉此行编译会报错 error: no matching function for call to 'Rectangle::Rectangle()'Rectangle(int x, int y): width(x), height(y){} //重载构造函数int area() {return width*height;}//声明友元函数duplicate()friend Rectangle duplicate(const Rectangle&); //是一个函数声明,所以行尾必须加分号。去掉friend编译会报错 error: 'int Rectangle::width' is private within this context
};Rectangle duplicate(const Rectangle& param){ //参数是另外一个对象param的引用Rectangle res;res.width = param.width*2; //通过友元可以实现对其他对象param的私有成员width的访问res.height = param.height*2; //通过友元可以实现对其他对象param的私有成员height的访问return res;
}int main(){Rectangle foo; //使用默认构造函数创建对象fooRectangle bar(2, 3); //使用重载构造函数创建对象bar//foo和bar都是同一个类型Rectangle类的对象,你是你,我是我,没有友元关系时,你不能访问我的私有成员,我也不能访问你的私有成员。foo = duplicate(bar); //使用友元函数修改foo对象的值,修改成功cout << "foo's area:" << foo.area() << endl; //查看foo的面积return 0;
}
编译运行
D:\YcjWork\CppTour>gpp c2001D:\YcjWork\CppTour>g++ c2001.cpp -o c2001.exeD:\YcjWork\CppTour>c2001
foo's area:24D:\YcjWork\CppTour>
运行截屏
(全文完)