如何覆盖父类的静态变量。
所以我有父类
class DatabaseItem
{
static int instanceCount;
DatabaseItem()
{
instanceCount++;
}
};
如果我有 2 个继承自 DatabaseItem 的类,我希望每个类都记录它们的类只存在多少个实例。我该怎么做?
所以:
class Person : public DatabaseItem
{
// how do I make sure when I make the call int numOfpeople = Person::instanceCount;
// that I only get the number of people objects that exist & not all the DatabaseItem
// objects that exist?
};
class FoodItem : public DatabaseItem
{
// how do I make sure when I make the call int numOffoodItems = FoodItem::instanceCount;
// that I only get the number of FoodItem objects that exist & not all the DatabaseItem
// objects that exist?
};
编辑回应评论
是的,但是,上面只是一个例子,如果我这样做,那么我有很多重复的代码......
所以:
class DatabaseItem
{
public:
static unsigned int instanceCount;
static Vector <unsigned int> usedIDs;
unsigned int ID;
DatabaseItem()
{
ID = nextAvailableID();
usedIDs.add( ID );
DatabaseItem::instanceCount++;
}
DatabaseItem( unsigned int nID )
{
if ( isIDFree( nID ) )
{
ID = nID;
}
else ID = nextAvailableID();
usedIDs.add( ID );
DatabaseItem::instanceCount++;
}
bool isIDFree( unsigned int nID )
{
// This is pretty slow to check EVERY element
for (int i=0; i<usedIDs.size(); i++)
{
if (usedIDs[i] == nID)
{
return false;
}
}
return true;
}
unsigned int nextAvailableID()
{
unsigned int nID = 0;
while ( true )
{
if ( isIDFree( ID ) )
{
return nID;
}
else nID++;
}
}
};
class Person {
public:
static unsigned int instanceCount;
static Vector <unsigned int> usedIDs;
unsigned int ID;
Person()
{
ID = nextAvailableID();
usedIDs.add( ID );
Person::instanceCount++;
}
Person( unsigned int nID )
{
if ( isIDFree( nID ) )
{
ID = nID;
}
else ID = nextAvailableID();
usedIDs.add( ID );
Person::instanceCount++;
}
bool isIDFree( unsigned int nID )
{
// This is pretty slow to check EVERY element
for (int i=0; i<usedIDs.size(); i++)
{
if (usedIDs[i] == nID)
{
return false;
}
}
return true;
}
unsigned int nextAvailableID()
{
unsigned int nID = 0;
while ( true )
{
if ( isIDFree( ID ) )
{
return nID;
}
else nID++;
}
}
};
.. 然后我必须为 FoodItem、coffeeRun 重写相同的代码....
最佳答案
使用模板来避免在每个构造函数中更新实例计数等所有此类问题。
template<class T>
struct Instance
{
static unsigned int count;
Instance () { count ++; }
Instance (const Instance& o) { count ++; }
};
template<class T>
unsigned int Instance<T>::count = 0;
现在这个模板可以被任何类继承,你需要计算它们的实例:
class DatabaseItem : public Instance<DatabaseItem> {};
class Person : public DatabaseItem, Instance<Person> {};
class FoodItem : public DatabaseItem, Instance<FoodItem> {};
就是这样!
只要声明了一个类对象,它就会完成它的工作。它可以按如下方式使用:
DatabaseItem *pD = new DatabaseItem[5];
Person obj[10];
cout<<Instance<DatabaseItem>::count<<endl; // 5 + 10 = 15
cout<<Instance<Person>::count<<endl; // 10
您不必在任何地方更新计数。
关于c++ - 如何覆盖父类的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5738154/