【发布时间】:2011-04-21 00:25:55
【问题描述】:
如何覆盖父类的静态变量。
所以我有父类
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?
};
EDIT回应cmets
是的,但是,上面只是一个例子,如果我这样做,那么我有很多重复的代码......
所以:
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 重写相同的代码....
【问题讨论】:
-
为每个派生类创建一个静态的..不需要重写。
-
您不覆盖它,但您可以通过在派生类中创建同名变量来隐藏它。
-
@Tomalak Geret'kal 如果我将 DatbaseItem 的变量设为虚拟会怎样?所以 virtual static unsigned int instanceCount; ?那么子分类器必须为此创建一个变量?
-
@Mack:函数成员可以是虚拟成员,而不是数据成员。
-
@Tomalak Geret'kal 感谢您的回复。有没有其他方法可以解决我的问题?
标签: c++ inheritance subclass