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);
    }
  • 相关阅读:
    bzoj2763 [JLOI]飞行路线 分层图最短路
    [模板]分块/可修改莫队 (数颜色种类)
    gcd步数
    洛谷2378 因式分解 字符串
    bzoj1090 字符串折叠
    洛谷1034 NOIP2002 矩形覆盖
    Codeforces#441 Div.2 四*题
    SPFA的小优化
    洛谷1073 NOIP2009 最优贸易
    bzoj2100 [Usaco2010 DEC]Apple Delivery苹果贸易
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/13341005.html
Copyright © 2011-2022 走看看