• C++ 访问私有成员——友元函数和友元类


    我们之前说到过,一个类中的私有成员变量或者函数,在类外是没有办法被访问的。但是,如果我们必须要访问该怎么办呢?这就要用到友元函数或者友元类了。

    而友元函数和友元类,就相当于一些受信任的人。我们在原来的类中定义友元函数或者友元类,告诉程序:这些函数可以访问我的私有成员。

    C++通过过friend关键字定义友元函数或者友元类。

    友元类

    1. Date.h

    #ifndef DATE_H
    #define DATE_H
    
    class Date {
    public:
        Date (int year, int month, int day) {
            this -> year = year;
            this -> month = month;
            this -> day = day;
        }
        friend class AccessDate;
    
    private:
        int year;
        int month;
        int day;
    };
    #endif // DATE_H

    2. main.cpp

    #include <iostream>
    #include "Data.h"
    
    using namespace std;
    
    class AccessDate {
    public:
        static void p() {
            Date birthday(2020, 12, 29);
            birthday.year = 2000;
            cout << birthday.year << endl;
        }
    };
    
    int main()
    {
        AccessDate::p();
        return 0;
    }

    运行结果:

    友元函数

    #include <iostream>
    
    using namespace std;
    
    class Date {
    public:
        Date (int year, int month, int day) {
            this -> year = year;
            this -> month = month;
            this -> day = day;
        }
        friend void p();
    
    private:
        int year;
        int month;
        int day;
    };
    
    void p() {
        Date birthday(2020, 12, 29);
        birthday.year = 2000;
        cout << birthday.year << endl;
    }
    
    int main()
    {
        p();
        return 0;
    }

    运行结果:

  • 相关阅读:
    卡特兰数列(蒟蒻的学习笔记)
    10月7日 蒟蒻的流水账
    10月6日 蒟蒻的流水账
    10月5日 蒟蒻的流水账
    10月4号 蒟蒻的流水账
    2017 10 14(吐槽初赛)
    2017 10 13
    个人介绍
    luogu P1156 垃圾陷阱
    模板之矩阵快速幂(luogu P3390【模板】矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/13024532.html
Copyright © 2020-2023  润新知