C++基础-友元函数(friend class)
标签:using protected ++ some 基础 str eth 当当 prot
当基类中的函数被protected的时候,只有继承的子类才能访问,为了使得非继承的类也可以使用,使用friend class (类名)来进行操作
#include 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 "kiss" name endl;
}
void Lover::ask(Lover *lover, string something){
cout "ask" name "do" 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 //因为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
评论