1、友元介绍
如果是一个类的友元,那可以访问一个类的所有成员及函数。但是这个友元函数不是这个类的成员函数。
2、友元函数
为什么能提高效率?如果不用友元的话,那就需要类提供两个接口来访问两个私有的成员,这样相对来说运行效率变慢了。
#include <iostream>
using namespace std;
class Point
{
friend double Distance(const Point& p1, const Point& p2);
//{
// return 0; // 友元函数的定义是在类外的,即使在这边给出实现,也没用
//}
public:
Point(int x, int y);
private:
int x_;
int y_;
};
Point::Point(int x, int y) : x_(x), y_(y)
{
}
double Distance(const Point& p1, const Point& p2)
{
double dx = p1.x_ - p2.x_;
double dy = p2.y_ - p2.y_;
return sqrt(dx * dx + dy * dy);
}
int main(void)
{
Point p1(3, 4);
Point p2(6, 8);
cout << Distance(p1, p2);
return 0;
}
3、友元函数注意事项
4、友元类
#include <iostream>
using namespace std;
class Television
{
friend class TeleController; // 声明TeleController为Television的友元类
public:
Television(int volume, int channel) : volume_(volume), channel_(channel)
{
}
private:
int volume_;
int channel_;
}
class TeleController
{
public:
void VolumeUp(Television& tv)
{
tv.volume_ += 1;
}
void VolumeDown(Television& tv)
{
tv.volume_ -= 1;
}
void ChannelUp(Television& tv)
{
tv.channel_+= 1;
}
void ChannelDown(Television& tv)
{
tv.channel_-= 1;
}
}
int main(void)
{
Television tv(1, 1);
TeleController tc;
tc.VolumeUp(tv);
return 0;
}
注意:如果是在.h和.cpp文件中的话,可以使用这样的前向声明,这样相比于include "Television.h"体积会小一点。
5、友元类的注意事项
A是B的友元类(在B类中friend class A),B向A公开了它所有的成员,A能访问B的所有成员;但是这不代表B也是A的友元类,B不能直接访问A的私有成员。
A是B的友元类,B又是C的友元类,并不代表A是C的友元类。
A是B的友元类,C继承自A,并不代表C是B的友元类。