全局函数做友元
作用:使类外函数或类访问类内私有属性
方法:在类内加友元函数声明:friend void func();
#include <iostream>
#include <string>
using namespace std;
class Building
{
friend void text(); //将访问私有成员的全局函数设为友元,全局函数就能访问私有成员
public:
string m_settingroom;
Building()
{
m_settingroom = "客厅";
m_bedroom = "卧室";
}
private:
string m_bedroom;
};
void text()
{
Building building;
cout << "正在访问" << building.m_settingroom << endl;
cout << "正在访问" << building.m_bedroom << endl; //m_bedroom作为私有成员不能在类外被普通全局函数访问
}
int main()
{
text();
return 0;
}
类做友元
作用:另一个类可以访问类的私有属性
方法:friend class Person;
#include <iostream>
#include <string>
using namespace std;
class GoodGay1
{
public:
Building *m_building;
GoodGay1();
void visit();
};
class Building
{
friend class GoodGay1; //将访问私有成员的类设为友元,类就能访问私有成员
public:
string m_settingroom;
Building()
{
m_settingroom = "客厅";
m_bedroom = "卧室";
}
private:
string m_bedroom;
};
GoodGay1::GoodGay1()
{
m_building = new Building;
}
//在函数名之前声明作用域
void GoodGay1::visit()
{
cout << "正在访问" << m_building -> m_settingroom << endl;
cout << "正在访问" << m_building -> m_bedroom << endl; //m_bedroom作为私有成员不能在类外被普通类访问
}
void text()
{
GoodGay1 goodgay1;
goodgay1.visit();
}
int main()
{
text();
return 0;
}
成员函数做友元
作用:使成员函数可以访问类中的私有属性
方法:friend void Person:: func(){};
#include <iostream>
#include <string>
using namespace std;
class Building;
class GoodGay2
{
public:
Building *m_building;
GoodGay2();
void visit1();
void visit2();
};
class Building
{
friend void GoodGay2::visit2(void); //将另一个类的成员函数设为友元,成员函数才能访问私有成员
public:
string m_settingroom;
Building()
{
m_settingroom = "客厅";
m_bedroom = "卧室";
}
private:
string m_bedroom;
};
GoodGay2::GoodGay2()
{
m_building = new Building;
}
//在函数名之前声明作用域
void GoodGay2::visit1()
{
cout << "正在访问" << m_building -> m_settingroom << endl;
// cout << "正在访问" << m_building -> m_bedroom << endl; //不是友元的类中 成员函数不能访问另一个类中的私有成员
}
void GoodGay2::visit2()
{
cout << "正在访问" << m_building -> m_settingroom << endl;
cout << "正在访问" << m_building -> m_bedroom << endl; //不是友元的类中,将成员函数设置为友元才能访问另一个类中的私有成员
}
void text()
{
GoodGay2 goodgay2;
goodgay2.visit1();
goodgay2.visit2();
}
int main()
{
text();
return 0;
}