目录
<0>.C++ 类中可以有 public、protected、private 三种属性的成员。
<1>.外部类可以通过实例化对象,可以访问public成员。
<2>.只有本类中的函数可以访问本类的 private 成员。
可以使外部类访问当前类的public、protected、private全部属性的成员函数和成员变量.
在当前类以外定义的、不属于当前类的函数也可以在类中声明,但要在前面加 friend 关键字,这样就构成了友元函数。
友元函数可以是不属于任何类的成员函数,也可以是其他类的成员函数。
友元函数可以访问当前类中的所有成员,包括 public、protected、private 属性的。
- #include
- using namespace std;
-
- class Box{
- public:
- Box(int wid): m_width(wid){
- cout << "wid = " << wid <
- }
- //定义test_friend函数是Box类的友元函数,Box类的所有成员都可以通过它来访问,包括private和
- protected属性的。
- friend void test_friend(Box box);
-
- protected:
- void setWidth(int width){
- m_width = width;
- cout << "width = " << width <
- }
-
- private:
- int m_width;
- };
-
- void test_friend(Box box){
- //printWidth是Box类的友元,可以直接访问Box类的任何成员,包括private成员变量和成员函数
- box.setWidth(66);
- printf("xxx------>%s(), m_width = %d\n",__FUNCTION__,box.m_width);
- }
-
- int main( ){
- Box box(55);
-
- test_friend(box);
- return 0;
- }
2.友元类
<1>.友元类定义
C++的friend关键字,不仅可以将一个函数声明为一个类的“朋友”,还可以将整个类声明为另一个类的“朋友”,这就是友元类。友元类中的所有成员函数都是另外一个类的友元函数。
如果将类B声明为类A的友元类,那么类 B 中的所有成员函数都是类 A 的友元函数,可以访问类 A 的所有成员,包括 public、protected、private 属性的。
<2>.程序例子
- #include
- using namespace std;
-
- //提前声明Address类
- class Address;
-
- class Student{
- public:
- Student(char *name): m_name(name){
- printf("Student::m_name = %s\n", m_name);
- }
-
- void show(Address *addr);
-
- private:
- char *m_name;
- };
-
- class Address{
- public:
- Address(char *addr): m_addr(addr){
- //printf("Address::m_addr = %s\n", m_addr);
- }
- //将Student类声明为Address类的友元类,可以访问类Address的所有成员,包括public、protected、private属性的.
- friend class Student;
- private:
- void test_private(){
- printf("xxx----->Address::%s(), line = %d\n",__FUNCTION__,__LINE__);
- }
- char *m_addr;
-
- protected:
- void test_protected(){
- printf("xxx----->Address::%s(), line = %d\n",__FUNCTION__,__LINE__);
- }
- };
-
- void Student::show(Address *addr){
- cout<< "private::m_addr = " << addr->m_addr <
- addr->test_private();
- addr->test_protected();
- }
-
- int main(){
- Student *stu = new Student("ZhangSan");
- Address *addr = new Address("china");
-
- stu->show(addr);
-
- return 0;
- }
-
相关阅读:
【洛谷题解/NOI2002】P2421/NOI2002荒岛野人
软考 系统架构设计师系列知识点之特定领域软件体系结构DSSA(7)
Go语言的单元测试与基准测试详解
java 各种架构图汇总
Mind2Web: Towards a Generalist Agent for the Web 论文解读
需求响应|动态冰蓄冷系统与需求响应策略的优化研究(Matlab代码实现)
无胁科技-TVD每日漏洞情报-2022-11-18
Unity3d 预制体引用的模型被覆盖找回
Acwing 暑假每日一题——. 正方形数组的数目
leetcode:782. 变为棋盘【数学找规律 + 模拟】
-
原文地址:https://blog.csdn.net/u010164190/article/details/128174687