所有元素都指向同一个对象
All elements point to same object
我正在尝试创建一个不同对象的数组。但是,我注意到,每当我从数组中更改一个对象时,所有元素都会收到该更改。显然,我只希望该索引处的对象接收到更改。下面是我的代码:
//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。
任何想法?非常感谢。
问题是tag
和valid
是全局变量,因此被类的所有实例共享。您需要将它们转换为实例变量(即类的非static
数据成员)。
相关文章:
- 我想访问std::unique_ptr中的一个特定元素
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 从多个源构造一个对象,包括一个对象向量
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 包装一个对象并假装它是一个 int
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 选择一个元素而不是一个对象的数组的原因
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 从C++数组中选择一个随机元素
- 在C++中,我如何创建一个数组,数组中大小为10的每个元素都指向一个对象
- 对一个对象上的每个元组元素调用函数,不进行递归