2

我正在尝试制作一组​​不同的对象。但是,我注意到每当我从数组中更改一个对象时,所有元素都会收到该更改。显然,我只希望该索引处的对象接收更改。这是我的代码:

//Creates the array pointer
cacheStats **directMappedTable1024Bytes = new cacheStats *[31];
//Initializes the array with cacheStats objects
    for (int i=0; i<31; i++)
{
    table[i] = new cacheStats();
}

//Test: Changing element of one object in the array
directMappedTable1024Bytes[5]->setTag(55);
cout << directMappedTable1024Bytes[22]->checkTag(); //should output 0

缓存统计代码:

#include "cacheStats.h"
int tag;
int valid;
using namespace std;
cacheStats :: cacheStats (int t, int v)
{
tag = t;
valid = v;
}
cacheStats :: ~cacheStats()
{
}
void cacheStats :: setTag (int cacheTag)
{
tag = cacheTag;
}
void cacheStats:: setValidBit (int validBit)
{
valid = validBit;
}
int cacheStats :: checkValid()
{
return valid;
}
int cacheStats :: checkTag()
{
return tag;
}

结果 cout 输出 55​​,而它本应输出 0。例如,如果我将前一行更改为 setTag(32),它将输出 32。

有任何想法吗?非常感谢。

4

1 回答 1

5

问题是tagvalid是全局变量,因此由类的所有实例共享。您需要将它们转换为实例变量(即static类的非数据成员)。

于 2013-04-28T19:52:14.953 回答