目录
<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;
- }
-
相关阅读:
linux文件类型
qml实现路径绘制且可编辑
PyQt5中的layout布局
深入浅出Spring Boot接口
北京化工大学历年真题整理:没考上,换了个学校,但还是在北京~哈哈
【es8-es11】新特性
Spring Security 集成 Authing CAS 认证(一)
汽车数字化转型:存储驱动创新未来
git的使用场景
C语言程序——Switch分支选择程序
-
原文地址:https://blog.csdn.net/u010164190/article/details/128174687