成员函数和友元函数对比完成同一个实例
源程序:
#include <iostream>
#include <cmath>
using namespace std;
class Pixel;
class Test
{
public:
void printX(Pixel p);
};
class Pixel
{
private:
int x,y;
public:
Pixel(int x0,int y0)
{
x=x0;
y=y0;
}
void printxy()
{
cout<<"pixel:("<<x<<","<<y<<")"<<endl;
}
double getDist1(Pixel p); //成员函数
friend double getDist(Pixel p1,Pixel p2); //友元函数
friend void Test::printX(Pixel p);
};
double Pixel::getDist1(Pixel p) //成员函数的定义
{
return sqrt((this->x-p.x)*(this->x-p.x)+(this->y-p.y)*(this->y-p.y));
}
void Test::printX(Pixel p)
{
cout<<"x="<<p.x<<"\ty="<<p.y<<endl;
}
double getDist(Pixel p1,Pixel p2) //友元函数的定义
{
double xd=double(p1.x-p2.x);
double yd=double(p1.y-p2.y);
return sqrt(xd*xd+yd*yd);
}
int main()
{
Pixel p1(0,0),p2(10,10);
p1.printxy();
p2.printxy();
cout<<"(p1,p2)间距离="<<p1.getDist1(p2)<<endl;
//cout<<"(p1,p2)间距离="<<getDist(p1,p2)<<endl;
//Test t;
//cout<<"从友元函数中输出---"<<endl;
//t.printX(p1);
//t.printX(p2);
return 1;
}