朋友成员(距离)

    xiaoxiao2025-05-22  12

    实现求距离函数的三种版本:分别利用成员函数、友元函数和一般函数求两点间距离的函数,并设计main()函数完成测试。

    #include<iostream> #include<cmath> using namespace std; class CPoint { private: double x; // 横坐标 double y; // 纵坐标 double d; public: CPoint(double xx=0,double yy=0):x(xx),y(yy){} friend void show1(CPoint &p); void distance(int x,int y); double get_d(); void show2(); }; double CPoint::get_d() { return d; } void CPoint::distance(int x,int y) { d=sqrt(x*x+y*y); } void CPoint::show2() { cout<<"类输出:"<<d<<endl; } void show(CPoint &p) { cout<<"普通输出:"<<p.get_d()<<endl; } void show1(CPoint &p) { cout<<"朋友输出:"<<p.d<<endl; } int main() { int x,y; char ch; CPoint p; cout<<"输入点的坐标(距离表示点到原点的距离):"<<endl; cin>>x>>ch>>y; p.distance(x,y); p.show2(); show(p); show1(p); return 0; }

    运行结果:

    小结:

    类成员能够直接访问私有数据成员,朋友成员不属于类,但是也可以以p.d进行私有数据成员的访问,但是一般函数只能通过类中的共有成员函数对类的私有数据成员进行访问。

    刚刚遇到了小麻烦,使得自己得出的最终结果为零。

    是这样的:

    定义函数double distance(int,int),通过计算得出距离值,直接通过返回值返回给函数distance,但是在show()函数中调用的时候直接cout<<distance(x,y);但是在构造函数中默认x,y的值都为零,在cout的时候等于把0赋值给x,y所以输出的结果为零,将之前的计算结果覆盖了,导致了计算结果的错误。

    转载请注明原文地址: https://ju.6miu.com/read-1299145.html
    最新回复(0)