当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。

相关推荐
拳里剑气2 分钟前
C++算法:二分查找
c++·算法·二分查找·学习方法
故事和你9122 分钟前
洛谷-算法1-7-搜索2
数据结构·c++·算法·leetcode·深度优先·动态规划·图论
不爱吃炸鸡柳27 分钟前
C++ 进阶:unordered_map 与 unordered_set 超全详解(哈希容器实战)
开发语言·c++·哈希算法
wengqidaifeng1 小时前
第十七届蓝桥杯C/C++软件赛B组算法题讲解
c语言·c++·蓝桥杯
道剑剑非道1 小时前
【C++ 仿 MFC 反射系统】
开发语言·c++·mfc
晓纪同学2 小时前
EffctiveC++_第三章_资源管理
开发语言·c++·算法
沐雪轻挽萤2 小时前
6. C++17新特性-编译期 if 语句 (if constexpr)
开发语言·c++
apcipot_rain3 小时前
【天梯赛】2026天梯赛模拟赛——题解
开发语言·c++·算法·蓝桥杯·天梯赛
-To be number.wan3 小时前
重新认识一下“私有继承”
c++·学习
江奖蒋犟3 小时前
【C++】红黑树
开发语言·c++