所有元素都指向相同的对象

问题描述:

我想制作一个不同的对象数组。但是,我注意到,每当我从数组中更改一个对象时,全部元素都会收到该更改。显然,我只想要该索引处的对象接收更改。 这是我的代码:所有元素都指向相同的对象

//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输出55,当它应该输出0。如果我改变前一行到setTag(32)例如,它将输出32.

任何想法? 非常感谢。

+0

将源发布到'cacheStats'?我猜你没有正确使用成员变量,但很难说。 – 2013-04-28 19:49:57

+0

确定它现在发布。 – s123 2013-04-28 19:52:02

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

+0

修复它。非常感谢。 – s123 2013-04-28 19:59:20