那位高手来为小弟指点迷津
做了好久都没做出来
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
double x;
double y;
public:
Point(double a,double b)
{
x=a;
y=b;
}
friend double dist(Point a,Point b);
};
double dist(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void main()
{
Point p1(1,2);
Point p2(5,2);
cout<<dist(p1,p2)<<endl;
}
如果将友元函数friend double dist(Point a,Point b);改为Point类的公有成员函数Point ::dist(point &b)
但要让函数的功能不变,该怎么修改?
[解决办法]
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
double x;
double y;
public:
Point(double a,double b)
{
x=a;
y=b;
}
static double dist(Point a,Point b);
};
double Point::dist(Point a,Point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
void main()
{
Point p1(1,2);
Point p2(5,2);
cout<<Point::dist(p1,p2)<<endl;
}
[解决办法]
我把它改成静态成员函数,普通的成员函数不好改,即使能改个人感觉没有意义