/***************************************************************\
* Copyright (c) 2009 eryar All rights reserved. *
* *
* File : Main.CPP *
* Date : 2009-01-19 19:00 *
* Author : eryar@163.com *
* *
* Description: *
* 编写一个程序,设计一个点类Point,求两个点之间的距离。 *
\***************************************************************/
#include
#include
using namespace std;
class Point{
public:
Point(double _x = 0, double _y = 0) : x(_x), y(_y) { cout<<"[class Point default constructor]"<
~Point() { cout<<"[class Point default destructor ]"<
//friend float Distance(const Point &, const Point &);
private:
friend float Distance(const Point &, const Point &);
float x;
float y;
}; // End of Point class
float Distance(const Point &p1, const Point &p2)
{
float distance = 0;
float DeltaX = 0;
float DeltaY = 0;
DeltaX = p2.x - p1.x;
DeltaY = p2.y - p1.y;
DeltaX *= DeltaX;
DeltaY *= DeltaY;
distance = sqrt(DeltaX + DeltaY);
return distance;
}
int main(int argc, char *argv[])
{
Point PointOne, PointTwo;
PointOne.SetPoint(6, 8);
PointOne.ShowPoint();
PointTwo.ShowPoint();
cout<<"The distance between two point is : "
<
return 0;
}
/*
笔记:
1. 友元函数可以访问类中的的私有数据成员, 与在类中声明的位置无关;
2. 当函数参数为类时,应尽量设置为引用类型, 这样可以提高性能;
3. 当对象本体和实体一致时,可以使用默认的拷贝构造函数;
*/
#include
#include
using namespace std;
class Point
{
public:
Point(double x,double y) //构造函数初始化Px,Py
{
Px = x; Py = y;
}
friend double Distance(Point p1,Point p2); //友元函数可以访问类的私有成员
private:
double Px,Py;
};
double Distance(Point p1,Point p2) //求距离函数
{
double result;
result = sqrt( pow(p1.Px-p2.Px,2) + pow(p1.Py-p2.Py,2) );//距离公式
return result;
}
void main()
{
Point p1(1,2), p2(1.5,2);
cout<<"p1与p2的距离是:"<
一楼已经提供了完整的代码了。