您的位置:首页 > 编程语言 > C语言/C++

C++第3次上机实验报告(友元函数二题)

2016-04-10 18:34 549 查看
/*
* 文件名称: bulabula
* 作    者:  郝荣雅
* 完成日期: 2016  年 4    月 10   日
* 版 本 号:v1.0
* 对任务及求解方法的描述部分:利用三种方式求两点距离
* 输入描述:
* 问题描述:
* 程序输出:
* 问题分析:
* 算法设计:
*/

1.(友元类)

#include<iostream>

#include<cmath>

using namespace std;

class Point

{

public:
Point(double xx,double yy)
{   
x1=xx;
y1=yy;
cout<<x1<<","<<y1<<endl;
}
friend void Distance(Point&Pointa,Point&Pointb);

private:
double x1;
double y1;
double dd;

};

void Distance(Point&Pointa,Point&Pointb)

{
double dx=Pointa.x1 -Pointb.x1 ;
double dy=Pointa.y1 -Pointb.y1 ;
double dd=sqrt(dx*dx+dy*dy);
cout<<"两点距离"<<dd<<endl;

}

void main()

{
Point a(5,7),b(1,4);
Distance(a,b);

}

(一般函数)

#include<iostream>

#include<cmath>

using namespace std;

void main()

{
double x1,x2;
double y1,y2;

    double dx,dy,dd;
cin>>x1>>y1>>x2>>y2;
dx=(x1-x2)*(x1-x2);
dy=(y1-y2)*(y1-y2);
dd=sqrt(dx+dy);
cout<<"两点坐标距离"<<dd;

}

(成员函数)

#include<iostream>

#include<cmath>

using namespace std;

class Point

{

public:
Point(double xx1,double yy1,double xx2,double yy2);
void distance();
void show();

private:
double x1,x2;
double y1,y2;

    double dd;

};

Point::Point(double xx1,double yy1,double xx2,double yy2)

{
x1=xx1,x2=xx2,y1=yy1,y2=yy2;

    cout<<x1<<","<<y1<<"   "<<x2<<","<<y2<<endl;

}

void Point::distance ()

{

    double dx,double dy;
dx=(x1-x2)*(x1-x2);
dy=(y1-y2)*(y1-y2);
dd=sqrt(dx+dy);

}

void Point::show ()

{
cout<<"diatance:"<<dd<<endl;

}

void main()

{
Point Point(5,7,1,4);
Point.distance ();
Point.show ();

}

2.运行结果







3.心得体会

其实最大的心得体会是友元函数那个,感觉是新的,对象的建立,以及对私有成员的访问;

4.知识点总结

友元函数可以访问私有成员和其他成员,但是访问时不能直接默认引用数据成员,必须使用对象进行引用

在main函数中对于友元函数的访问是不用加friend的,而且不用通过对象来引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: