本文介绍了计算单个派生类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够对属于同一类层次结构的类的实例进行计数.
I'd like to be able to count instances of classes that belong in the same class hierarchy.
例如,假设我有这个:
class A;
class B: public A;
class C: public B;
然后我有这段代码
A* tempA = new A;
B* tempB = new B;
C* tempC = new C;
C* tempC2 = new C;
printf(tempA->GetInstancesCount());
printf(tempB->GetInstancesCount());
printf(tempC->GetInstancesCount());
结果应打印
1
1
2
the result of that should print
1
1
2
理想情况下,应在内部进行计数.每个类(而不是某种管理器)都应该知道它有多少个实例.
The counting, ideally, should be done internally. Each class, and not some kind of manager, should know how many instances it has.
有什么想法吗?
谢谢!
推荐答案
建议的解决方案存在一个问题:创建B时,将自动调用A构造函数,从而增加A的计数.
There is a problem with proposed solutions: when you create B you A constructor will be called automatically and thus increment count of A.
class A
{
public:
A(bool doCount = true)
{
if (doCount)
++instanceCount_;
}
static std::size_t GetInstanceCount()
{
return instanceCount_;
}
virtual ~A(){}
private:
static std::size_t instanceCount_;
};
class B: public A
{
public:
B(bool doCount = true):A(false)
{
if (doCount)
++instanceCount_;
}
static std::size_t GetInstanceCount()
{
return instanceCount_;
}
private:
static std::size_t instanceCount_;
};
std::size_t A::instanceCount_ = 0;
std::size_t B::instanceCount_ = 0;
这篇关于计算单个派生类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!