C++ 友元
来源:互联网 发布:家用菜刀 知乎 编辑:程序博客网 时间:2024/06/17 17:01
类可以允许其他类或函数访问它的非公有成员,方法是令其他类或函数成为它的友元(friend)。
应用对象: 函数 ——- 友员函数
类 ——- 友员类
功 能:提供了在类的外部访问类中的
所有成员的途径
弊 端:一定程度上破坏了类的封装性
备 注:友员关系不受类中访问修饰符的限制
1.友元函数
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
//声明 show() 是Test的友元函数
friend void show(Test &t);
};
void show(Test &t)
{
cout << “t.m_data = ” << t.m_data << endl;
return;
}
int main(int argc,char *argv[])
{
Test t(123);
show(t);
return 0;
}
2.友元类
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
//声明Brother是Test的友元类friend class Brother;
};
class Brother
{
public:
Brother(){}
~Brother(){}
void show(Test &t){ cout << "t.m_data = " << t.m_data << endl; return;}
};
int main(int argc,char *argv[])
{
Test t(123);
Brother b;
b.show(t);
return 0;
}
3.友元类间的关系
友员类性质:1.不能继承 - 父亲的朋友不是你的朋友
2.不能传递 - 朋友的朋友不是你的朋友
3.不能反转 - 你的就是我的,但是我的还是我的
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
friend class Father;
friend class Brother;
void show(Test &t)
{
cout << “Test data=” << t.m_data << endl;
return;
}
};
class Brother
{
public:
Brother(){}
~Brother(){}
friend class Son;
};
class Father
{
public:
Father(){}
~Father(){}
void show(Test &t){ cout << "Father data=" << t.m_data << endl; return;}
};
class Son:public Father
{
public:
Son(){}
~Son(){}
void show(Test &t){ cout << "Son data=" << t.m_data << endl; return;}
};
int main(int argc,char *argv[])
{
Test t(123);
Father f;
f.show(t);
// Son s;
// s.show(t); //error
return 0;
}
- C++(一)友元
- [C++]友元学习
- [c++]友元函数
- [c++] 友元详解
- 【C++】友元函数
- c++:友元函数
- C++:友元函数
- C++:友元
- C/C++ 友元
- 【C++】友元函数
- C++:友元
- C++----友元
- 【C++】C++友元
- C++_友元函数
- C++_友元函数
- C++_友元函数
- C++_友元函数
- C++_友元函数
- intellij idea中每次修改jsp等文件时不用再重新启动tomcat的方法
- spring源码学习---bean获取
- 关于PHP框架学习的选择
- 关于windows连接虚拟机中的linux
- 多态
- C++ 友元
- 面试算法-------确定两个字符串乱序同构
- 3.3Javascript函数-调用函数
- java中String\十六进制String\byte[]之间相互转换函数
- Two Sum
- Majority Element
- VS2010配置DirectX 11
- acm书中题目 p-16
- 从二维向量跟虚数的区别到欧拉公式,复指数函数