您的位置:首页 > 其它

3-6 静态数据成员与静态成员函数

2017-12-08 17:42 525 查看
Submit Statistic

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

静态数据成员是为了实现“共享”

静态数据成员:不管定义几个对象,都共用一个内存空间

#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Point
{
private:
double x, y;
static int count;//静态数据成员
public:
Point(double xx = 0, double yy = 0)
{
x = xx;
y = yy;
count++;//在构造函数中对count累加,所有对象共同维护一个count
}
~Point()
{
cout<<"Deconstructor point x="<<x<<endl;
}
void showpoint()
{
cout<<"x="<<x<<","<<"Y="<<y<<endl;
}
static void show()//静态成员函数
{
cout<<"the number of points is "<<count<<endl;
}

};
int Point::count = 0;//静态数据成员的初
4000
始化,使用类名限定,在类外进行初始化
int main()
{
Point a(0, 0), b(3, 0), c(5, 0);
a.showpoint();
Point::show();//输出对象的个数
//最后调用三次析构函数,注意析构函数的顺序
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: