文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C++ 友元

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;

}

排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载