当C++的static遇上了继承

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

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,结果会发生变化吗?

class B : public A

当然会了,结果如下:

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

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

	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就好了

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。

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-08 11:58:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-08 11:58:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-08 11:58:01       82 阅读
  4. Python语言-面向对象

    2024-06-08 11:58:01       91 阅读

热门阅读

  1. 【每日一函数】uname 函数介绍及代码演示

    2024-06-08 11:58:01       27 阅读
  2. vue2 computed 、watch --vue3 computed 、watch

    2024-06-08 11:58:01       27 阅读
  3. jQuery:一站式指南

    2024-06-08 11:58:01       25 阅读
  4. 【讯为Linux驱动开发】4.文件私有数据

    2024-06-08 11:58:01       28 阅读
  5. 自动化喷涂生产线方案四

    2024-06-08 11:58:01       23 阅读
  6. 大数据如何更好地助力乡村振兴战略的实施?

    2024-06-08 11:58:01       31 阅读
  7. 快速删除 node_modules

    2024-06-08 11:58:01       33 阅读