C++对对象个数进行计数

//利用静态数据成员的数据共享这个性质
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();

以圆柱体的类生产对象为例

 

//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;
//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所以“看起来”没问题

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值