复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//利用静态数据成员的数据共享这个性质 class Widget { public: Widget() { ++count; } Widget(const Count&) { ++count; } ~Widget() { --count; } static size_t getCount() { return count; } private: static size_t count; }; //然后在main外写上 size_t Widget::count = 0; //在main里写上 cout << Cylinder::getCount();
以圆柱体的类生产对象为例
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52//Cylinder.h #include <iostream> using namespace std; #define PI 3.1415926 class Cylinder { public: static int obj_count; double radius; double height; Cylinder(double r, double h); Cylinder(const Cylinder& a); ~Cylinder(); double Get_Volume(); double Get_Surface(); static int get_num_of_objects(){return obj_count;} }; //定义构造函数 Cylinder ::Cylinder(double r, double h) {radius = r; height = h; obj_count++;} //定义拷贝构造函数 Cylinder ::Cylinder(const Cylinder& a) { radius = a.radius; height = a.height; obj_count++; } //定义析构函数 Cylinder ::~Cylinder() {obj_count--;} //求体积 double Cylinder ::Get_Volume() { return PI * radius * radius * height; } //求表面积 double Cylinder ::Get_Surface() { return (PI * radius * radius * 2) + (2 * PI * radius * height); } void display(Cylinder c) { cout << "n第" << Cylinder::obj_count-1 <<"个:"<< endl; cout << "半径为" << c.radius << endl; cout << "高为" << c.height << endl; cout << "体积为" << c.Get_Volume() << endl; cout << "表面积为" << c.Get_Surface() << endl; } int Cylinder::obj_count=0;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18//main.cpp #include <iostream> #include "Cylinder.h" using namespace std; int main() { Cylinder c1(2, 3); display(c1); Cylinder c2 = c1; display(c2); Cylinder c3(4, 5); display(c3); c3.~Cylinder(); cout<<"n类的个数为:"<<Cylinder::get_num_of_objects(); return 0; }
输出为2,3-1得到的
有两个困惑:
1、初始化和输出obj_count都放main里会报错“definition or redeclaration of 'obj_count' not allowed inside a function”
2、第一次调用一个类会计数变为2?之后都还是加一。。我写的是Cylinder::obj_count-1所以“看起来”没问题
最后
以上就是超级烤鸡最近收集整理的关于C++对对象个数进行计数的全部内容,更多相关C++对对象个数进行计数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复