多年前就粉c++,认为这是黑客专门用的语言,到现在这种情怀仍有增无减;那时朦朦胧胧的看到友元函数这个词顿时觉得深不可测;其实通过下面的例子我们不难发现,友元函数就是在类方法之外,通过函数访问类的私有成员的一种方法声明。不像人话是么?先看这样一个例子
- 定义了一个坐标点的类用于计算两点间的距离(参见解析几何之类的数学书),该类有两个属性x坐标,y坐标
#pragma once
class mypoint
{
private:
int x;
int y;
public:
mypoint();
mypoint(int x, int y);
int getx()
{
return this->x;
}
int gety()
{
return this->y;
}
~mypoint();
};
- 类方法的实现
#include "mypoint.h"
mypoint::mypoint()
{
}
mypoint::mypoint(int x, int y)
{
this->x = x;
this->y = y;
}
mypoint::~mypoint()
{
}
- 在主程序文件中,突然想定义一个函数,通过获得两个点的(x,y)计算点之间的距离
#include<iostream>
#include "mypoint.h"
#include "math.h"
using namespace std;
double getdistance(mypoint &p1, mypoint &p2)
{
int ret_x = p1.getx() - p2.getx();//只能通过公共方法访问私有属性
int ret_y = p1.gety() - p2.gety();
return sqrt(ret_x*ret_x+ ret_y * ret_y);
}
void main()
{
mypoint p1(2, 3);
mypoint p2(3, 4);
cout << "两点间的距离是:"<< getdistance(p1,p2) << endl;
system("pause");
}
很明显,想获得x,y的坐标就得通过类的公共方法getx(),gety()-----这就频繁的使用压栈和出栈操作结果带来性能的开销,为了能在外部定义的函数直接访问私有属性,友元函数应孕而生
- 改变一:类方法的声明文件
#pragma once
class mypoint
{
friend double getdistance(mypoint &p1, mypoint &p2);//在类的声明体哪里声明都可以
private:
int x;
int y;
public:
mypoint();
mypoint(int x, int y);
int getx()
{
return this->x;
}
int gety()
{
return this->y;
}
~mypoint();
};
- 改变二,主程序文件的实现
#include<iostream>
#include "mypoint.h"
#include "math.h"
using namespace std;
double getdistance(mypoint &p1, mypoint &p2)
{
int ret_x = p1.x - p2.x;//在类声明外也能实现对私有成员的访问
int ret_y = p1.y - p2.y;
return sqrt(ret_x*ret_x+ ret_y * ret_y);
}
void main()
{
mypoint p1(2, 3);
mypoint p2(3, 4);
cout << "两点间的距离是:"<< getdistance(p1,p2) << endl;
system("pause");
}
来源:https://www.cnblogs.com/saintdingspage/p/12020142.html