demo_4_friend_function_1.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 33 行

CPP
33
字号

//**************************************************************
//友元函数

#include <iostream.h>
#include <math.h>

class Point	//Point类定义
{
public:	//外部接口
	Point(int xx=0, int yy=0) {X=xx;Y=yy;} //构造函数
	int GetX() {return X;}
	int GetY() {return Y;}
	friend float fDist(Point &a, Point &b);	//友元函数声明
private: //私有数据成员
	int X,Y;
};

float fDist(Point &p1, Point &p2) //友元函数实现,类对象引用参数
{
	double x=double(p1.X-p2.X);	//通过对象访问私有数据成员
	double y=double(p1.Y-p2.Y);

	return float(sqrt(x*x+y*y));
}
void main()	//主函数
{
	Point myp1(1,1),myp2(4,5); //定义Point类对象并调用构造函数初始化

	cout<<"The distance is: ";
	cout<<fDist(myp1,myp2)<<endl; //计算两点间的距离
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?