1. 程式人生 > 其它 >成員函式和友元函式對比完成同一個例項

成員函式和友元函式對比完成同一個例項

源程式:

#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;
}