通过本题目的练习可以掌握静态数据成员和静态成员函数的用法。
要求设计一个点类Point,它具有两个double型的数据成员x、y,和一个静态数据成员count,用以记录系统中创建点对象的数目。为该类设计构造函数和析构函数,在其中对count的值做修改,体现点的数目的动态变化。并为其添加一个静态成员函数showCount用以输出count的值;成员函数showPoint()用于输出点的信息。
确保你严格按照题目要求定义Point类和它的成员函数,我们将在你提交的代码后追加一段代码用来检查Point类的定义。如果你的代码没有完全按照题目要求,将可能引发编译错误。
输入描述
输入点的x坐标和y坐标,当x、y均为0的时候停止输入。
输出描述
输出输入的点的个数。
示例1:
输入:1 1
2 2
3 3
4 4
0 0
输出:4
// 代码来源:https://my.oschina.net/u/4255005/blog/3721857
#include <iostream>
using namespace std;
class Point {
public:
Point(double xx = 0.0, double yy = 0.0) :x(xx), y(yy) { count++; } // 构造函数1
Point(const Point &p);// 构造函数2
~Point();
static int showCount();
void showPoint();
private:
double x, y;
static int count;
};
int Point::count = 0;
Point::Point(const Point&p) // 构造函数2的初始化
{
x = p.x;
y = p.y;
count++;
}
Point::~Point() // 析构函数的初始化
{
count--;
}
int Point::showCount()
{
return Point::count;
}
void Point::showPoint()
{
cout << x << " " << y << endl;
}
int main()
{
double a, b;
Point *save_point[100]; // 超纲!!!指针,数组
int i = 0;
while (cin >> a >> b)
{
if (a == b && a == 0)
{
cout << Point::showCount() << endl;
break;
}
save_point[i] = new Point(a, b);
i++;
}
// system("pause");
return 0;
}
// 以下代码作废
/*
#include<iostream>
using namespace std;
class Point
{
public:
Point(double a=0.0, double b=0.0); // 构造函数
~Point(){count--;} // 析构函数
double showPoint();
static int showCount();
private:
double x,y;
static int count;//静态数据成员的声明
};
Point::Point(double a, double b) // 构造函数类外初始化
{
x=a;
y=b;
count++;
}
double Point::showPoint()
{
cout << "X=" << x << ",Y=" << y <<endl;
}
int Point::showCount()
{
// cout << count << endl;
return count;
}
int Point::count=0;//静态数据成员的定义和初始化
int main()
{
double x,y;
// cin >> x >> y;
// Point p(0,0);
// int i=0;
if(cin >> x >> y)
// cin>>x>>y;
Point p(x,y);
// Point p1(0,0);
// p1.ShowPoint();
// Point p2(3,0);
// Point p3(5,0);
else
cout << Point::showCount() << endl;//类名::函数名 调用静态成员函数
return 0;
}
*/