1)代码实现:

#include #include using namespace std;

class Point{ private: int x; int y; public: Point(int a=0, int b=0):x(a),y(b){} //默认值构造函数 int getX() {return x;} int getY() {return y;} double Dist() {return sqrt(xx+yy);} //重载函数1 double Dist() const {return sqrt(xx+yy);} //重载函数2 };

2)主函数代码实现:

int main(){ const Point myp1(1,1), myp2(4,5); //定义常对象 Point p1(2,3), p2(6,8); //定义普通对象 cout<<"myp1和myp2两点间距离:"<<myp1.Dist()<<" "<<myp2.Dist()<<endl; cout<<"p1和p2两点间距离:"<<p1.Dist()<<" "<<p2.Dist()<<endl; return 0; }

输出结果:

myp1和myp2两点间距离:1.41421 6.40312 p1和p2两点间距离:3.60555 10.6301

说明:常对象不允许修改对象成员,因此在常对象的成员函数中,需要加上const关键字;而普通对象可以修改对象成员,不需要加上const关键字。

1定义一个class Point类其中含有2个私有数据成员分别是点的两个的坐标值xy;含有三个成员函数分别是:int getX返回点的x坐标值int getY返回点的y坐标值double Dist计算两点间距离; 成员函数重载分别为:分别为:double Dist和double Distconst 并要求double Distconst形式参数为常对象2主函数定义Point类的普通对象和常对象以:

原文地址: https://www.cveoy.top/t/topic/b5Wc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录