• 友元函数


    类的友元函数是定义在类外部,但有权访问类的所有私有成员和保护成员。尽管友元函数的原型有在类的定义中出现过,但友元函数并不是成员函数。

    友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。在这种情况下,整个类及其所有成员都是友元。如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字friend,如下所示:

    class Box
    {
        double width;
    public:
        double length;
        friend void printWidth(Box box);
        void setWidth(double wid);    
    };

    声明类ClassTwo的所有成员函数作为类的ClassOne的友元,需要在类ClassOne的定义中放置如下声明:

    friend class ClassTwo;
    /***
    friend.cpp
    ***/
    #include<iostream>
    using namespace std;
    
    class Box
    {
        double width;
    public:
        friend void printWidth(Box box);
        void setWidth(double wid);
    };
    
    void Box::setWidth(double wid)
    {
        width = wid;
    }
    
    void printWidth(Box box)
    {
        cout << "Width of box : " << box.width << endl;
    }
    
    int main()
    {
        Box box;
        
        box.setWidth(10.0);
        printWidth(box);
        return 0;
    }

    运行结果:

    exbot@ubuntu:~/wangqinghe/C++/20190807$ ./friend

    Width of box : 10

    因为友元函数没有this指针,则参数要有三种情况:

    1. 要访问非static成员时,需要对象作为参数;
    2. 要访问static成员或者全局变量时,不需要对象作为参数;
    3. 如果做参数的对象是全局对象,则不需要对象做参数。

    友元类的使用

    /***
    classfriend.cpp
    ***/
    #include<iostream>
    using namespace std;
    
    class Box
    {
        double width;
    public:
        friend void printWidth(Box box);
        friend class BigBox;
        void setWidth(double wid);
    };
    
    class BigBox
    {
    public:
        void Print(int width, Box &box)
        {
            box.setWidth(width);
            cout << "Width of box: " << box.width << endl;
        }
    };
    
    void Box::setWidth(double wid)
    {
        width = wid;
    }
    
    void printWidth(Box box)
    {
        cout << "Width of box : " << box.width << endl;
    }
    
    int main()
    {
        Box box;
        BigBox big;
        
        box.setWidth(10.0);
    
        printWidth(box);
    
    big.Print(20,box);
        return 0;
    }

    运行结果:

    exbot@ubuntu:~/wangqinghe/C++/20190807$ ./classfriend

    Width of box : 10

    Width of box: 20

  • 相关阅读:
    2:(sql语言的数据类型)
    4:关系数据库标准语言sql(sql概述:功能,特点)
    毕业设计:反射,枚举
    毕业设计:阶段性总结
    3.9易错题
    3.8(关系代数表达查询)
    3.7(附加的关系运算)
    3.5(关系的完整性约束)、(关系代数的五种基本运算:选择和投影(关于行运算和列运算的概念还不清晰))
    3.4(从E-r概念模型到关系模型即DBMS直接支持的数据模型)
    php 如何获取图片后缀和可变函数的使用实战
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11316598.html
Copyright © 2020-2023  润新知