友元

本文介绍了C++中友元的概念及其作用,解释了为何需要友元机制来提高程序效率和实现不同类之间的数据共享。文章还探讨了友元的特点,如非对称性和非传递性。

友元:

1. 为什么需要友元?

类具有封装恶化信息隐藏的特性,所以只有类的成员函数才能访问类的私有成员。当非成员函数要访问类中的私有成员时,就必须将数据成员都定义成公有的,这破坏了隐藏的特性。而且在对某些成员函数多次调用时,由于参数传递,类型检查和安全性检测都需要时间开销,从而影响到了运行效率。所以提出友元。可以使非成员函数访问类中的私有成员。

2.友元概念和分类

友元可以是一个函数也可以是一个类,前者称为友元函数,后者称为友元类。

3. 友元的作用:

友元提供了不同类的成员之间、类的成员函数与一般函数之间进行数据共享的机制。

4.友元的特点:

友元关系不具有对称性,即A是B的友元,而B不一定是A的友元。

友元关系也不具有传递性,即A是B的友元,B是C的友元,但A不一定是C的友元。

友元关系不能被继承。

### 友元声明的基本概念 在 C++ 中,友元声明允许一个或函数访问另一个的私有和受保护成员。这打破了的封装性,但在某些情况下是必要的,比如实现之间的紧密合作[^1]。 ### 友元函数声明 友元函数是一个不属于任何的普通函数,但它可以访问的私有和受保护成员。以下是一个不使用额外数组的示例: ```cpp #include <iostream> class Rectangle { private: int width; int height; public: Rectangle(int w, int h) : width(w), height(h) {} // 友元函数声明 friend int area(const Rectangle& rect); }; // 友元函数定义 int area(const Rectangle& rect) { return rect.width * rect.height; } int main() { Rectangle rect(5, 3); std::cout << "Area: " << area(rect) << std::endl; return 0; } ``` 在这个示例中,`area` 函数是 `Rectangle` 友元函数,它可以直接访问 `Rectangle` 的私有成员 `width` 和 `height`,且没有使用额外的数组[^1]。 ### 友元声明 友元是一个,它的所有成员函数都可以访问另一个的私有和受保护成员。以下是一个示例: ```cpp #include <iostream> class Rectangle { private: int width; int height; public: Rectangle(int w, int h) : width(w), height(h) {} // 友元声明 friend class RectanglePrinter; }; class RectanglePrinter { public: void printArea(const Rectangle& rect) { std::cout << "Area: " << rect.width * rect.height << std::endl; } }; int main() { Rectangle rect(5, 3); RectanglePrinter printer; printer.printArea(rect); return 0; } ``` 在这个示例中,`RectanglePrinter` 是 `Rectangle` 友元,它的 `printArea` 函数可以直接访问 `Rectangle` 的私有成员 `width` 和 `height`,同样没有使用额外的数组[^1]。 ### 友元成员函数声明 可以指定一个的某个成员函数作为另一个友元。以下是示例: ```cpp #include <iostream> class Rectangle; class RectanglePrinter { public: void printArea(const Rectangle& rect); }; class Rectangle { private: int width; int height; public: Rectangle(int w, int h) : width(w), height(h) {} // 友元成员函数声明 friend void RectanglePrinter::printArea(const Rectangle& rect); }; // 友元成员函数定义 void RectanglePrinter::printArea(const Rectangle& rect) { std::cout << "Area: " << rect.width * rect.height << std::endl; } int main() { Rectangle rect(5, 3); RectanglePrinter printer; printer.printArea(rect); return 0; } ``` 在这个示例中,`RectanglePrinter` 的 `printArea` 成员函数是 `Rectangle` 友元,它可以访问 `Rectangle` 的私有成员,且不使用额外数组[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值