所有元素都指向同一个对象

All elements point to same object

本文关键字:一个对象 元素      更新时间:2023-10-16

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

//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

cacheStats代码:

#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应该输出0时,它输出55。例如,如果我将前一行更改为setTag(32),它将输出32。

任何想法?非常感谢。

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

相关文章: