码迷,mamicode.com
首页 > 编程语言 > 详细

C++基础-友元函数(friend class)

时间:2020-07-19 23:16:52      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:using   protected   ++   some   基础   str   eth   当当   prot   

当基类中的函数被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 << "\n当当当:传说的路人甲登场...\n";
    others.kiss(&girlfriend);
}

 

C++基础-友元函数(friend class)

标签:using   protected   ++   some   基础   str   eth   当当   prot   

原文地址:https://www.cnblogs.com/my-love-is-python/p/13341005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!