C++中friend的使用(friend function and friend class) .
来源:互联网 发布:三步登天软件 编辑:程序博客网 时间:2024/05/24 03:45
转自:http://blog.csdn.net/andy_yf/article/details/7062347
对于一个没有定义public访问权限的类,能够让其他的类操作它的私有成员往往是有用的。例如你写了一段binary tree的代码,Node是节点类,如果能够让连接多个节点的函数不需要调用public方法就能够访问到Node的私有成员的话,一定是很方便的。
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 Node { private: int data; int key; // ... friend class BinaryTree; // class BinaryTree can now access data directly};
这样BinaryTree就可以直接访问Node中的private的成员了,就像下面这样:
- 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
- }
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的成员变量。(这就是友元类和友元函数的区别)
- 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
- HBase 和 MongoDB在设计上的区别
- poj1703 Find them, Catch them [并查集]
- apache 压力测试工具ab
- http编程URL的Get与post
- 外网访问花生壳局域网中服务器问题
- C++中friend的使用(friend function and friend class) .
- ubuntu下的c/c++环境搭建(转)
- uva11529
- 获取当前线程的id号 gettid()
- C#实现系统托盘图标
- MIME类型
- 【SHELL】4 批量添加用户
- Mina学习笔记(2) HelloWorld(TCP/IP)
- 花生壳域名绑定动态ip注意事项