C++中friend的使用(friend function and friend class)
来源:互联网 发布:linux mv 创建文件夹 编辑:程序博客网 时间:2024/05/20 00:15
对于一个没有定义public访问权限的类,能够让其他的类操作它的私有成员往往是有用的。例如你写了一段binary tree的代码,Node是节点类,如果能够让连接多个节点的函数不需要调用public方法就能够访问到Node的私有成员的话,一定是很方便的。这样BinaryTree就可以直接访问Node中的private的成员了,就像下面这样:
Friend Classes(友元类)
C++中的friend关键字其实做这样的事情:在一个类中指明其他的类(或者)函数能够直接访问该类中的private和protected成员。你可以这样来指明:
friend class aClass;注意:friend在类中的声明可以再public、protected和private的如何一个控制域中,而不影响其效果。例如,如果你在protected域中有这样的声明,那么aClass类同样可以访问该类的private成员。
这有一个例子:
- class Node
- {
- private:
- int data;
- int key;
- // ...
- friend class BinaryTree; // class BinaryTree can now access data directly
- };
- class BinaryTree
- {
- private:
- Node *root;
- int find(int key);
- };
- int BinaryTree::find(int key)
- {
- // check root for NULL...
- if(root->key == key)
- {
- // no need to go through an accessor function
- return root->data;
- }
- // perform rest of find
- }
Friend Functions(友元函数)
友元函数和友元类的作用是一样的,它允许一个函数不需要通过其public接口就能够访问到类中的private和protected成员变量。你可以这样去声明:
friend return_type class_name::function(args);这里有一个例子:
class Node { private: int data; int key; // ... friend int BinaryTree::find(); // Only BinaryTree's find function has access};这样find方法就可以直接访问Node中的私有成员变量了,而BinaryTree中的其他的方法去不能够直接的访问Node的成员变量。(这就是友元类和友元函数的区别)
0 0
- C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class) .
- C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class)
- C++中friend的使用(friend function and friend class)
- [C++] C++中friend的使用(friend function and friend class)
- C++ friend function and friend class
- friend class & function
- c++中friend function
- [C++] friend class
- C++::Class Friend
- c++中friend class
- friend
- friend
- Friend
- Friend
- friend
- 基础学习笔记之opencv(2):haartraining前将统一图片尺寸方法
- Apache Portable Runtime (APR) based Native library for Tomcat
- Python中为什么没有++和--(自增/减)
- 关于html 界面中元素隐藏的几种方法
- 判断js是否被禁用
- C++中friend的使用(friend function and friend class)
- ie9 scrollbar中hover 高度增高的bug
- 南邮 OJ 1095 奇特的图形
- Same Tree
- C++实现两个字符串之间的Levenshtein Distance(编辑距离)
- 0-1排序引理
- Struts2组合spring
- 常用做action recognition 的数据集介绍
- linux 下编译安装Qt