live long and prosper
《C++程序设计教程》笔记之类友元
在C++语言中,类也可以作为友元。
在下面例子中,创建了一个B类和G类。
B类中含有两个属性,sittingroom是公共属性,livingroom是私有属性。在G类中创建一个B类,并能够访问B类中的元素。
1、无友元,访问公共和私有属性
#include<iostream>
#include<string>
using namespace std;
class B;
class G{
public:
B *building;
G();
public:
void visit();
};
class B{
class G;
public:
B(){
sittingroom="sittingroom";//客厅
livingroom="livingroom";//卧室
}
public:
string sittingroom;//客厅作为公共属性
private:
string livingroom;//卧室作为私有属性
};
G::G() {
building=new B;
}
void G::visit() {//访问B类中的元素
cout<<"---"<<building->sittingroom<<endl;
cout<<"---"<<building->livingroom<<endl;
}
void test01(){//测试函数,验证visit()函数
G gg;
gg.visit();
}
int main()
{
test01();
return 0;
}
在这个例子中,让visit()函数访问B中的公共函数和私有属性,结果编译器报错:
‘std::string B::livingroom’ is private within this context
visit()函数无法访问私有变量
2、建立友元
#include<iostream>
#include<string>
using namespace std;
class B;
class G{
public:
B *building;
G();
public:
void visit();
};
class B{
friend class G;//在B类中,建立G的友元类,让B类对G类“友好”
public:
B(){
sittingroom="sittingroom";
livingroom="livingroom";
}
public:
string sittingroom;
private:
string livingroom;
};
G::G() {
building=new B;
}
void G::visit() {
cout<<"---"<<building->sittingroom<<endl;
cout<<"---"<<building->livingroom<<endl;
}
void test01(){
G gg;
gg.visit();
}
int main()
{
test01();
return 0;
}
编译结果为:
—sittingroom
—livingroom