例5-9常引用做形参
#include<iostream> #include<cmath> using namespace std; class Point { public: Point(int x=0,int y=0):x(x),y(y){} int getX() { return x; } int getY() { return y; } friend float dist(const Point& p1, const Point& p2); private: int x, y; }; float dist(const Point& p1, const Point& p2) { double x = p1.x - p2.x; double y = p1.y - p2.y; return static_cast<float>(sqrt(x * x + y * y)); } int main() { const Point myp1(1, 1), myp2(4, 5); cout << "The distance is:"; cout << dist(myp1, myp2) << endl; return 0; }
例5-10具有静态数据、函数成员的Point类,多组织文件
class Point { public: Point(int x = 0, int y = 0) :x(x), y(y) { count++;} Point(const Point& p); ~Point() { count--; } int getX()const { return x; } int getY()const { return y; } static void showCount(); private: int x, y; static int count; }; #include"Point.h" #include<iostream> using namespace std; int Point::count = 0; Point::Point(const Point& p) :x(p.x), y(p.y) { count++; } void Point::showCount() { cout << "Object count=" << count << endl; } #include"Point.h" #include<iostream> using namespace std; int main() { Point a(4, 5); cout << "Point A:" << a.getX() << "," << a.getX(); Point::showCount(); Point b(a); cout << "Point B:" << b.getX() << "," << b.getY(); Point::showCount(); }
标签:24,count,const,Point,int,return,打卡,include From: https://www.cnblogs.com/xuechenhao173/p/17429269.html