zoukankan      html  css  js  c++  java
  • C++基础-友元函数(friend class)

    当基类中的函数被protected的时候,只有继承的子类才能访问,为了使得非继承的类也可以使用,使用friend class (类名)来进行操作

    #include <iostream>
    
    using namespace std;
    
    class Lover{
    public:
        Lover(string theName);
        void kiss(Lover *lover);
        void ask(Lover *lover, string something);
    
    protected:
        string name;
        friend class Others; //构造友元函数, 使得Others可以调用name属性 
    };
    Lover::Lover(string theName) {
        name = theName;
    }
    
    void Lover::kiss(Lover *lover) {
        cout << name << "kiss" << lover->name << endl;
    }
    
    void Lover::ask(Lover *lover, string something){
        cout << name << "ask" << lover->name << "do" << something << endl;
    }
    
    class Boyfriend:public Lover {
    public:
        Boyfriend(string theName);
    };
    
    Boyfriend::Boyfriend(string theName) : Lover(theName){ //进行有参数的继承
    
    }
    class Girlfriend:public Lover {
    public:
        Girlfriend(string theName);
    };
    
    Girlfriend::Girlfriend(string theName) : Lover(theName){}
    
    class Others {
    public:
        Others(string theName);
        void kiss(Lover *lover);
    protected:
        string name;
    };
    
    Others::Others(string theName) {
        name = theName;
    }
    void Others::kiss(Lover *lover) {
        cout << name << "亲一下" << lover->name << endl; //因为name是protected, 如果没有友元就不能进行访问 
    }
    
    
    int main() {
    
        Boyfriend boyfriend("A君");
        Girlfriend girlfriend("B妞");
    
        Others others("路人甲");
    
        girlfriend.kiss(&boyfriend);
        girlfriend.ask(&boyfriend, "洗衣服啦");
    
        cout << "
    当当当:传说的路人甲登场...
    ";
        others.kiss(&girlfriend);
    }
  • 相关阅读:
    linux(不会考特别难,牢记下面即可)
    ajax
    Javascript 和 Jquery
    开发环境及配置
    网络协议考点
    面向对象考点
    会话控制
    文件操作
    正则表达式
    自定义函数和内部函数
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/13341005.html
Copyright © 2011-2022 走看看