我正在尝试实现一个类家族,这些类跟踪每个类存在多少个实例。因为所有这些类都有这种行为,所以我想把它拉到一个超类中,这样我就不必对每个类重复实现了。考虑以下代码:
class Base
{
protected static int _instances=0;
protected int _id;
protected Base()
{
// I would really like to use the instances of this's class--not
// specifically Base._instances
this._id = Base._instances;
Base._instances++;
}
}
class Derived : Base
{
// Values below are desired,
// not actual:
Derived d1 = new Derived(); // d1._id = 0
Derived d2 = new Derived(); // d2._id = 1
Derived d3 = new Derived(); // d3._id = 2
public Derived() : base() { }
}
class OtherDerived : Base
{
// Values below are desired,
// not actual:
OtherDerived od1 = new OtherDerived(); // od1._id = 0
OtherDerived od2 = new OtherDerived(); // od2._id = 1
OtherDerived od3 = new OtherDerived(); // od3._id = 2
public OtherDerived() : base() { }
}
如何实现每个类的实例计数器(与基类的计数器分开的计数器)?我试过混合静态和抽象(不编译)。请指教。