クラスごとに存在するインスタンスの数を追跡するクラスのファミリーを実装しようとしています。これらのクラスはすべてこの動作をするため、クラスごとに実装を繰り返す必要がないように、単一のスーパークラスに引き出したいと思います。次のコードを検討してください。
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() { }
}
クラスごとのインスタンスカウンター(基本クラスのカウンターとは別のもの)を実現するにはどうすればよいですか?静的と抽象を混合してみました(コンパイルされません)。お知らせ下さい。