友元概念
友元的目的就是让一个函数或者类 访问另外一个类中的私有成员
友元的关键字为 friend
友元的几种实现
- 全局函数做 友元
- 类做 友元
- 成员函数做 友元
- 重载函数做 友元
全局函数做 友元
#include<iostream>
using namespace std;
class Building
{
//Friend 全局函数 是 类 Building 的友元 ,可以访问私有属性
friend void Friend(Building *building);
public:
string SittingRoom;
Building()
{
SittingRoom = "客厅";
BedRoom = "卧室";
}
private:
string BedRoom;
};
void Friend(Building *building)
{
cout<<"朋友 "<<building->SittingRoom<<endl;
cout<<"朋友 "<<building->BedRoom<<endl;
}
void test()
{
Building building;
Friend(&building);
}
int main()
{
test();
return 0;
}
普通函数做 友元
即把一个 不属于任何类的普通函数作为某个类的友元函数
#include<iostream>
using namespace std;
class Date
{
int year,month;
public:
Date(int y,int m)
{
year = y;
month = m;
}
friend bool Equal(Date d1,Date d2);
};
bool Equal(Date d1,Date d2) //普通函数
{
return (d1.year == d2.year && d1.month == d2.month);
}
int main()
{
Date you(2020,1),my(2020,2);
if(Equal(you,my))
cout<<"1";
else cout<<"0";
return 0;
}
重载函数做友元
#include<iostream>
using namespace std;
class Complex
{
private:
double a,b;
public:
Complex():a(0.0),b(0.0){
}
Complex(double _a,double _b)
{
a = _a;
b = _b;
}
friend Complex operator-(Complex A,Complex B);
void Print()
{
cout<<"("<<a<<","<<b<<")";
}
};
Complex operator-(Complex A,Complex B)
{
A.a -= B.a;
A.b -= B.b;
return A;
}
int main()
{
Complex A(5.1,2.2);
Complex B(3.3,2.5);
A = B - A;
A.Print();
return 0;
}
类做 友元
当类A把另一个类B声明为自己的friend之后,B中所有成员函数就都是A的友元函数,可以访问A中成员变量,(A中定义B是友元,B能调用A的成员变量)
举例
#include<iostream>
using namespace std;
class Person; //因为Person是友元,在声明之前需定义
class Date
{
private:
int year,month,day;
public:
Date(int y,int m,int d)
{
year = y;
month = m;
day = d;
}
void Disp()
{
cout<<"您需要的日期信息:"<<endl;
cout<<year<<"-"<<month<<"-"<<day<<endl;
}
friend Person; //Person 是 Date 的友元 ,在此处声明了,所以在前面要定义一下
};
class Person
{
private:
string name;
public:
Person(string na)
{
name = na;
}
void Disp(Date d) //传入 Date 的 对象
{
d.Disp(); //调用Date的成员函数和数据成员
cout<<name<<"是";
cout<<d.year<<"年出生的\n"; //此处调用了Date的private 数据
}
};
int main()
{
Person p("张三");
Date birthday(2000,1,1);
p.Disp(birthday);
return 0;
}
说明
- 友元的关系是单向的。声明了类B是类A的友元,说明B能访问A的成员变量,但A不能访问B的 (题中Date类中设置了Person是友元,说明Person类可以调用Date类的private 数据,反之不能)
- 友元的关系不能传递。B是A的友元,C是B的友元,不代表C是A的友元。
- 友元的关系不能继承。
- 实际工作中一般不会把整个类声明为友元类