3-6 静态数据成员与静态成员函数
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
通过本题目的练习可以掌握静态数据成员和静态成员函数的用法
要求设计一个点类Point,它具有两个double型的数据成员x,y。和一个静态数据成员count ,用以记录系统中创建点对象的数目。为该类设计构造函数和析构函数,在其中对count的值做修改,体现点的数目的动态变化。并为其添加一个静态成员函数用以输出count的值;成员函数showPoint()用于输出点的信息。
并编写主函数,输出以下的内容。
Input
无
Output
Example Input
Example Output
x=0,Y=0 the number of points is 3 Deconstructor point x=5 Deconstructor point x=3 Deconstructor point x=0
Hint
Author
参考:http://blog.csdn.net/youth_mr6/article/details/53491121
#include <bits/stdc++.h>
using namespace std;
class point
{
private:
double x, y;
static int cnt; //注意静态变量与常变量的区别
public: //静态成员只能在类外进行初始化
point( double a = 0, double b = 0 ) //构造函数,输入点的位置并记录点的数量
{
cnt++;
x = a;
y = b;
}
~point() //析构函数
{
cout << "Deconstructor point x=" << x << endl;
}
static void print_cnt() //输出点的数量
{
cout << "the number of points is " << cnt << endl;
}
void print() //输出点
{
cout << "x=" << x << ",Y=" << y << endl;
}
};
int point::cnt = 0; //对静态成员变量进行初始化,并且只初始化一次
int main ()
{
point p1(0,0), p2(3), p3(5);
p1.print();
point::print_cnt();//静态成员函数的调用方式
return 0;
}