友元
关键字:friend
全局函数做友元
想要在全局函数中调用类中的私有成员变量则需要将函数声明在类内在声明一遍并加上friend关键字。
#include <iostream>
#include <string>
using namespace std;
class building{
friend void goodfriend(building *p);//加上此声明即可访问私有属性
public:
building(){
this->livingroom = "客厅";
this->bedroom = "房间";
}
string livingroom;
private:
string bedroom;
};
void goodfriend(building *p)//全局函数
{
cout << "好朋友正在访问:" << p->livingroom << endl;
cout << "好朋友正在访问:" << p->bedroom << endl;//可通过友元来访问
}
void test01(){
building b;
goodfriend(&b);
}
int main(void)
{
test01();
return 0;
}
类做友元
想要在一个类中访问另一个类的私有属性,则只需要在该类中声明另一个类,并在其前面加上关键字:friend
#include <iostream>
#include <string>
using namespace std;
class Building;//先声明一个类
class goodfriend
{
public:
goodfriend();//构造函数
void vist();//成员函数
private://私有属性
Building *building;
};
class Building
{
friend class goodfriend;//该声明可以让goodfriend类访问Bulding类
public://的私有属性
Building();//构造函数
string livingroom;
private:
string bedroom;
};
Building::Building()//类外通过构造函数初始化该类的成员变量
{
this->livingroom = "客厅";
this->bedroom = "卧室";
}
goodfriend::goodfriend()
{
building = new Building;
}
void goodfriend::vist()//类外写该成员函数
{
cout << "好朋友正在访问您的:" << building->livingroom << endl;
cout << "好朋友正在访问您的:" << building->bedroom << endl;
}
void test()
{
goodfriend p;//创建一个对象
p.vist();//调用函数
}
int main(void)
{
test();
return 0;
}
成员函数做友元
一个类的成员函数想要访问另一个类的私有属性,则必须在该类中进行声明(并表示是哪一个类的成员函数),在其声明前加上关键字:friend
#include <iostream>
#include <string>
using namespace std;
class Building;//先声明一个类
class goodfriend
{
public:
goodfriend();//构造函数
void vist();//成员函数
void vist2();
private://私有属性
Building *building;
};
class Building
{
friend void goodfriend::vist();//该声明可以让vist成员函数访问Bulding类的私有属性
public:
Building();//构造函数
string livingroom;
private:
string bedroom;
};
Building::Building()//类外通过构造函数初始化该类的成员变量
{
this->livingroom = "客厅";
this->bedroom = "卧室";
}
goodfriend::goodfriend()
{
building = new Building;
}
void goodfriend::vist()//类外写该成员函数
{
cout << "好朋友正在访问您的:" << building->livingroom << endl;
cout << "好朋友正在访问您的:" << building->bedroom << endl;
}
void goodfriend::vist2()//类外写该成员函数
{
cout << "好朋友正在访问您的:" << building->livingroom << endl;//公共的可以访问
// cout << "好朋友正在访问您的:" << building->bedroom << endl;未通过friend声明表示,不可访问其私有成员变量
}
void test()
{
goodfriend p;//创建一个对象
p.vist();//调用函数
p.vist2();
}
int main(void)
{
test();
return 0;
}