友元函数是在类中用关键字friend
修饰的非成员函数。友元函数可以是一个普通的函数,也可以是其他类的成员函数,虽然它不是本类的成员函数,但是在它的函数体中可以通过对象名访问类的私有和保护成员。
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
int x, y; // 私有数据成员
public:
Point(int x = 0, int y = 0) : x(x), y(y){}
int getX() {
return x;
}
int getY() {
return y;
}
friend float dist(Point &p1, Point &p2); // 友元函数声明
};
float dist(Point &p1, Point &p2){
double x = p1.x - p2.x;
double y = p1.y - p2.y;
return static_cast<float>(sqrt(x * x + y * y)); // static_cast是一个c++运算符,功能是把一个表达式转换为float类型。
}
int main(){
Point *point1 = new Point(1, 1); // 定义 Point 类的对象
Point *point2 = new Point(4, 5); // 定义 Point 类的对象
cout << "两点间的距离是:";
cout << dist(*point1, *point2) << endl; // 计算两点间的距离
delete point2;
delete point1;
return 0;
}
注:友元函数不仅可以是一个普通函数,也可以是另一个类的成员函数。友元成员函数的使用和一般友元函数的使用基本相同,只是要通过相应的类或对象名来访问。
#include<iostream>
using namespace std;
class girl{
private:
char name;
int age;
public:
girl(char n, int d){ //构造函数
name = n;
age = d;
}
friend void display(girl &x); //声明友元函数
};
void display(girl &x){ //类外定义 友元函数
cout << "姓名:" << x. name << "\n年龄:" << x.age << endl;
//girl类的友元函数能访问girl类对象的私有成员
}
int main(){
girl e('z', 18);
display(e); //调用友元函数
return 0;
}