例具有静态数据、成员函数的Point类
代码部分:
#include<iostream> using namespace std; class Point { private: int x, y; static int count; public: Point(int x=0,int y=0):x(x),y(y) { count++; } Point(Point& p) { x = p.x; y = p.y; count++; } ~Point() { count--; } int getX() { return x; } int getY() { return y; } static void showCount() { cout << "Object count=" << count << endl; } }; int Point::count = 0; int main() { Point a(4, 5); cout << "Point a:" << a.getX() << "," << a.getY(); Point::showCount(); Point b(a); cout << "Point B:" << b.getX() << "," << b.getY(); Point::showCount(); return 0; }
例5-6
题目描述:
使用友元函数计算两点间的距离。
代码部分:
#include<iostream> #include<cmath> using namespace std; class Point { private: int x, y; public: Point(int x = 0, int y = 0) :x(x), y(y) {}; int getX() { return x; } int getY() { return y; } friend float dist(Point& p1, 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() { Point myp1(1, 1), myp2(4, 5); cout << "The distance is:"; cout << dist(myp1, myp2) << endl; return 0; }
标签:count,return,22,Point,int,static,打卡,include From: https://www.cnblogs.com/xuechenhao173/p/17420711.html