阅读背景:

成员函数,友元函数和一般函数之区别

来源:互联网 
/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: object.cpp
* 作者:赵  洋
* 完成日期: 2013年4  月12  日
* 版本号: v1.0
* 输入描述:无
* 问题描述:一般函数,成员函数,友元函数求两点间的距离
* 程序输出:
*/
#include <iostream>
#include<cmath>
using namespace std;
class CPoint
{
private:
    double x;  // 横坐标
    double y;  // 纵坐标
public:
    CPoint(double xx=0,double yy=0):x(xx),y(yy) {}
    void display1(CPoint &); //成员函数声明
    friend void display2(CPoint &,CPoint &);  //友元函数声明
    double getx()
    {
        return x;
    }
    double gety()
    {
        return y;
    }
};
void display3(CPoint &,CPoint &);  //一般函数声明
void CPoint::display1(CPoint &p)  //成员函数的实现,dispaly1前加CPoint::
{
    double d;
    d=sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
    cout<<"两点间的距离为:"<<d<<endl;
}
void display2(CPoint &t1,CPoint &t2)  //友元函数的实现,dispaly2前不加Time::,并不是类的成员函数
{
    double d;
    d=sqrt((t1.x-t2.x)*(t1.x-t2.x)+(t1.y-t2.y)*(t1.y-t2.y));
    cout<<"两点间的距离为:"<<d<<endl;
}
void display3(CPoint &t1,CPoint &t2)  //一般函数的实现,dispaly1前加Time::
{
    double d;
    d=sqrt((t1.getx()-t2.getx())*(t1.getx()-t2.getx())+(t1.gety()-t2.gety())*(t1.gety()-t2.gety()));
    cout<<"两点间的距离为:"<<d<<endl;
}
int main()
{
    CPoint p1(10,13), p2(-5,6);
    p1.display1(p2);
    display2(p1,p2);
    display3(p1,p2);
    return 0;
}
/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: