C++ 友元
时间:2010-11-15 来源:luozhiyong131
/******************
普通函数作为友元函数
********************/
#include <iostream.h>
#include <math.h>
const double PI=3.14;
class Circle
{
private:
double x,y,r;
public:
Circle(double xx=0,double yy=0,double rr=0)
{
x=xx; y=yy; r=rr;
}
void display()
{
cout<<"\tCenter point:("<<x<<","<<y<<")"<<endl;
cout<<"\tRadius:"<<r<<endl;
cout<<"\tArea:"<<this->area()<<endl;
cout<<"\tCirculars:"<<this->circular()<<endl;
}
double area(){return PI*r*r;}
double circular(){return 2*PI*r;}
friend double distance(Circle &p1,Circle &p2);
};
double distance(Circle &p1,Circle &p2)
{
return(sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)));
}
void main()
{
Circle c1(1,1,1),c2(3,4,5);
cout<<"Cricle1: "<<endl;
c1.display();
cout<<"Cricle2: "<<endl;
c2.display();
cout<<"The distance is:"<<distance(c1,c2)<<endl;
}
/******************
成员函数作为友元函数
********************/
#include <iostream.h>
#include <math.h>
const double PI=3.14;
class Circle; //前向声明
class Calculate
{
public:
double distance(Circle &p1,Circle &p2);
};
class Circle
{
private:
double x,y,r;
public:
Circle(double xx=0,double yy=0,double rr=0)
{
x=xx; y=yy; r=rr;
}
void display()
{
cout<<"\tCenter point:("<<x<<","<<y<<")"<<endl;
cout<<"\tRadius:"<<r<<endl;
cout<<"\tArea:"<<this->area()<<endl;
cout<<"\tCirculars:"<<this->circular()<<endl;
}
double area(){return PI*r*r;}
double circular(){return 2*PI*r;}
friend double Calculate::distance(Circle &p1,Circle &p2); //声明友元函数
};
double Calculate::distance(Circle &p1,Circle &p2)
{
return(sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)));
}
void main()
{
Circle c1(1,1,1),c2(3,4,5);
Calculate cal;
cout<<"Cricle1: "<<endl;
c1.display();
cout<<"Cricle2: "<<endl;
c2.display();
cout<<"The distance is:"<<cal.distance(c1,c2)<<endl;
}
/*****************
****友元类使用****
******************/
#include <iostream.h>
#include <math.h>
const double PI=3.14;
class Circle; //前向声明
class Calculate
{
public:
double distance(Circle &p1,Circle &p2);
};
class Circle
{
private:
double x,y,r;
public:
Circle(double xx=0,double yy=0,double rr=0)
{
x=xx; y=yy; r=rr;
}
void display()
{
cout<<"\tCenter point:("<<x<<","<<y<<")"<<endl;
cout<<"\tRadius:"<<r<<endl;
cout<<"\tArea:"<<this->area()<<endl;
cout<<"\tCirculars:"<<this->circular()<<endl;
}
double area(){return PI*r*r;}
double circular(){return 2*PI*r;}
friend class Calculate; //声明友元类
};
double Calculate::distance(Circle &p1,Circle &p2)
{
return(sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)));
}
void main()
{
Circle c1(1,1,1),c2(3,4,5);
Calculate cal;
cout<<"Cricle1: "<<endl;
c1.display();
cout<<"Cricle2: "<<endl;
c2.display();
cout<<"The distance is:"<<cal.distance(c1,c2)<<endl;
}