zoukankan      html  css  js  c++  java
  • 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;
    }

    运行结果:

  • 相关阅读:
    java 动态代理
    android中几个很有用的的api
    android 静态和动态设置 Receiver的 android:enabled值
    一个文件查看你选择 Run as Android applications 都干了啥
    ViewStub 的使用
    Linux 常用命令速查
    android自定义View&&简单布局&&回调方法
    西厢记 随笔
    git 命令使用速查手册( 个人版)
    Arraylist源码分析:
  • 原文地址:https://www.cnblogs.com/bwjblogs/p/13024532.html
Copyright © 2011-2022 走看看