博客
关于我
友元函数与友元类
阅读量:636 次
发布时间:2019-03-14

本文共 1877 字,大约阅读时间需要 6 分钟。

1. 朋友函数

朋友函数需要在类中任意位置进行声明,与普通函数不同的是要加上friend关键字,并在类外进行实现。朋友函数并非类的成员函数,因此可以访问该类的私有成员。

朋友函数的特点

  • 可访问私有成员:朋友函数可以访问类的私有成员。
  • 没有this指针:朋友函数没有隐藏的this指针,因此参数列表中需要多一个类的参数。
  • 灵活性:由于没有this指针,朋友函数可以完成普通成员函数无法完成的操作。
  • 朋友函数优先级:朋友函数与static成员函数类似,无this指针,但friend函数的调用优先级低于static成员函数。
  • 可多个类的朋友:一个函数可以成为多个类的朋友函数。
  • 例子

    class Complex {public:    Complex(int real = 0, int imag = 0) : m_real(real), m_imag(imag) {}    ~Complex() {}    Complex operator+(int a) {        return Complex(m_real + a, m_imag);    }private:    int m_real;    int m_imag;};class ComplexFriend {public:    ComplexFriend(int real, int imag) : m_real(real), m_imag(imag) {}    ~ComplexFriend() {}private:    int m_real;    int m_imag;};friend Complex operator+(int a, const Complex& c) {    return Complex(a + c.m_real, c.m_imag);}friend Complex operator+(const Complex& c1, const Complex& c2) {    return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);}void main() {    Complex c, c1(1, 3);    c = c1 + 10;    c = 10 + c1;    c = c1 + c2;}

    2. 朋友类

    朋友类的所有成员函数都可以是另一个类的朋友函数,并可以访问另一个类的非公有成员。

    朋友类的特点

  • 单向性:朋友关系是单向的,不具有交换性。
  • 不传递性:如果B是A的朋友,C是B的朋友,则不能说明C是A的朋友。
  • 例子

    // 声明Time类为朋友类,Date类可以访问Time类的私有成员class Date {public:    Date(int year = 1900, int month = 1, int day = 1) :        _year(year), _month(month), _day(day), _t(9, 30, 45) {}    void SetTimeOfDate(int hour, int minute, int second) {        _t._hour = hour;        _t._minute = minute;        _t._second = second;    }private:    int _year;    int _month;    int _day;    Time _t;};friend class Time;
    class Time {public:    Time(int hour, int minute, int second) :        _hour(hour), _minute(minute), _second(second) {}private:    int _hour;    int _minute;    int _second;};friend class Date;
    void main() {    Time t1(11, 2, 3);    Date d1(2020, 3, 15);    Date d2 = d1;    d1.SetTimeOfDate(1, 10, 11);}

    总结

    朋友函数和朋友类为C++提供了灵活的访问控制机制,可以实现类间的非继承式的私有成员访问。然而,朋友关系具有单向性和不传递性,需要谨慎操作。

    转载地址:http://rsulz.baihongyu.com/

    你可能感兴趣的文章
    MySQL和SQL入门
    查看>>
    mysql在centos下用命令批量导入报错_Variable ‘character_set_client‘ can‘t be set to the value of ‘---linux工作笔记042
    查看>>
    Mysql在Linux运行时新增配置文件提示:World-wrirable config file ‘/etc/mysql/conf.d/my.cnf‘ is ignored 权限过高导致
    查看>>
    Mysql在Windows上离线安装与配置
    查看>>
    MySQL在渗透测试中的应用
    查看>>
    Mysql在离线安装时启动失败:mysql服务无法启动,服务没有报告任何错误
    查看>>
    Mysql在离线安装时提示:error: Found option without preceding group in config file
    查看>>
    MySQL基于SSL的主从复制
    查看>>
    Mysql基本操作
    查看>>
    mysql基本操作
    查看>>
    mysql基本知识点梳理和查询优化
    查看>>
    mysql基础
    查看>>
    Mysql基础 —— 数据基础操作
    查看>>
    mysql基础---mysql查询机制
    查看>>
    MySQL基础5
    查看>>
    MySQL基础day07_mysql集群实例-MySQL 5.6
    查看>>
    Mysql基础命令 —— 数据库、数据表操作
    查看>>
    Mysql基础命令 —— 系统操作命令
    查看>>
    MySQL基础学习总结
    查看>>
    mysql基础教程三 —常见函数
    查看>>