当C++的static遇上了继承

比如我们想要统计下当前类被实例化了多少次,我们通常会这么写

cpp 复制代码
class A
{
public:
	A() { Count_++; }
	~A() { Count_--; }
	int GetCount() { return Count_; }

private:
	static int Count_;
};

class B
{
public:
	B() { Count_++; }
	~B() { Count_--; }
	int GetCount() { return Count_; }

private:
	static int Count_;
};

int A::Count_ = 0;
int B::Count_ = 0;

int main()
{
	A a1, a2, a3;
	B b1, b2, b3, b4, b5;
	std::cout << a1.GetCount() << std::endl;
	std::cout << b1.GetCount() << std::endl;
}

输出理所当然的是 3 和 5。

1、现在做下小修改,让B继承自A,结果会发生变化吗?

cpp 复制代码
class B : public A

当然会了,结果如下:

毫不意外,因为B构造的时候就会调用A的构造函数,所以,A的Count_为8,B的Count_为5.

2、再次修改,用new的方式创建

cpp 复制代码
	A *a1 = new A, *a2 = new A, *a3 = new A;
	A *b1 = new B, *b2 = new B, *b3 = new B, *b4 = new B, *b5 = new B;
	std::cout << a1->GetCount() << std::endl;
	std::cout << b1->GetCount() << std::endl;

结果又发生变化了:

这是因为我们是定义A了来指向new出来的B, 那么 b1->GetCount()的时候其实是调用了类A的GetCount()。所以返回了8。

3、怎么样来获取实例化的B的数量呢?其实再增加一个virtual就好了

cpp 复制代码
class A
{
public:
	A() { Count_++; }
	~A() { Count_--; }
	virtual int GetCount() { return Count_; }

private:
	static int Count_;
};

class B : public A
{
public:
	B() { Count_++; }
	~B() { Count_--; }
	int GetCount() { return Count_; }

private:
	static int Count_;
};

结果又成了熟悉的8、 5。

相关推荐
ybzj.37 分钟前
2025年第十六届蓝桥杯省赛C/C++大学B组 个人题解
c++
量子炒饭大师1 小时前
【C++ 11】Cyber骇客 最后的一片净土 ——【C++11的 简单介绍 + 发展历史】历史唯物主义者带你理顺C++发展的由来
c++·dubbo·c++11
hetao17338371 小时前
2025-03-24~04-06 hetao1733837 的刷题记录
c++·算法
原来是猿1 小时前
Linux进程信号详解(三):信号保存
开发语言·c++·算法
2401_892070981 小时前
算法与数据结构精讲:最大子段和(暴力 / 优化 / 分治)+ 线段树从入门到实战
c++·算法·线段树·最大子段和
暴力求解2 小时前
C++ ---- String类(一)
开发语言·c++
暴力求解2 小时前
C++ --- STL简介
开发语言·c++
森G2 小时前
46、环境配置---------QChart
c++·qt
2301_803554523 小时前
三大编程语言(Python/Go/C++)项目启动全解析
c++·python·golang
wunaiqiezixin3 小时前
MyString类的常见面试问题
c++·面试