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

相关推荐
semicolon_hello9 分钟前
使用C++编写TCP服务端程序
服务器·网络·c++·tcp/ip
L小李要学习1 小时前
十一、作业
c语言·开发语言·c++
听听听搁浅1 小时前
数论知识(取模运算)
c++·数论
Ddddddd_1581 小时前
C++ | Leetcode C++题解之第216题组合总和III
c++·leetcode·题解
每天努力进步!1 小时前
LeetCode热题100刷题8:54. 螺旋矩阵、73. 矩阵置零、48. 旋转图像
c++·算法·leetcode·矩阵
观鉴词recommend1 小时前
【c++刷题笔记-贪心】day28: 134. 加油站 、 135. 分发糖果 、860.柠檬水找零 、 406.根据身高重建队列
c++·笔记·算法·leetcode
tnnnnt2 小时前
C++多线程学习笔记
c++·多线程
creative_mind2 小时前
My Greedy Algorithm(贪心算法)之路(一)
c++·算法·贪心算法
王红花x2 小时前
STL——list模拟实现
c++·学习·list
danaaaa4 小时前
算法力扣刷题记录 二十八【225. 用队列实现栈】
数据结构·c++·算法·leetcode·职场和发展