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

相关推荐
·present·1 天前
CSAPP(lecture 4_01)
c语言·c++
FPGA小迷弟1 天前
用 Claude Code 重构遗留系统:从评估到落地的完整实践指南
c++·python·ai·plotly·django·ai编程·claude
程序员-King.1 天前
【ROS1】Noetic 开发工作流程与常用命令
c++·ubuntu·ros
云深麋鹿1 天前
C++ | 基于红黑树实现mymap与myset
开发语言·c++
傲世仙尊1 天前
string增删查改-insert-erase-replace与find加substr组合技
c++
·present·1 天前
CSAPP(lecture 3)
c++
别动我齐刘海1 天前
机器人 C++ / 系统联调补强2——异常处理、Protobuf
linux·c++·人工智能·学习·算法·机器学习·机器人
basketball6161 天前
C++ 中字符串与常见类型的转换总结
开发语言·c++
等我调个Bug1 天前
C++智能指针通俗讲解
开发语言·c++
kyle~1 天前
时间同步 --- PTP 与 Scheduled Action Command
c++·数码相机·机器人·传感器