下次使用该功能时,计数器会被窃听
Counter gets bugged next time using the function
首先对标题感到抱歉,仅用一句话无法解释清楚..
我正在创建一个 object,它有一个数组和一个计数器来随时计算数组中有多少元素,但不知何故,每次我添加一个数字时计数器都会丢失它的值.
我正在使用以下函数将元素添加到数组中:
Heap operator+=(int newHeap)
{
this->arr[arr_counter] = newHeap;
cout<<newHeap<<" was added to the Heap"<<endl;
cout <<"Currect counter is:"<<arr_counter<<endl;
this->arr_counter++;
cout <<"Currect counter is:"<<arr_counter<<endl;
}
如您所见,在向数组中添加一个元素后,我将计数器加 1。
我主要运行的代码是:
Heap<int> hi(10);
int curr;
((hi += 3) += 2);
但不知何故,我得到以下输出:
10 was added to the integers heap!
3 was added to the Heap
Currect counter is:1
Currect counter is:2
2 was added to the Heap
Currect counter is:-2
Currect counter is:-1
下次我使用该函数时,是否有任何理由使计数器变为 -2?
如果有帮助,class 的其余部分就是这样定义的:
template <>
class Heap<int> {
public:
Heap (int x) {
arr[0]=x;
arr_counter=1;
cout<<this->arr[0]<< " was added to the integers heap!"<<endl;
}
//...some other functions
private:
int arr[10];
int arr_counter;
};
Heap operator+=(int newHeap)
应该是 Heap& operator+=(int newHeap)
并且需要 return *this
才能工作。 我认为代码 as-is 无法编译。 打开更高级别的编译器警告是个好习惯。
根据您发布的不完整代码,它可能是未初始化的变量问题,也可能是对象内存损坏(您是否在任何地方 memset 0?)
首先对标题感到抱歉,仅用一句话无法解释清楚..
我正在创建一个 object,它有一个数组和一个计数器来随时计算数组中有多少元素,但不知何故,每次我添加一个数字时计数器都会丢失它的值. 我正在使用以下函数将元素添加到数组中:
Heap operator+=(int newHeap)
{
this->arr[arr_counter] = newHeap;
cout<<newHeap<<" was added to the Heap"<<endl;
cout <<"Currect counter is:"<<arr_counter<<endl;
this->arr_counter++;
cout <<"Currect counter is:"<<arr_counter<<endl;
}
如您所见,在向数组中添加一个元素后,我将计数器加 1。
我主要运行的代码是:
Heap<int> hi(10);
int curr;
((hi += 3) += 2);
但不知何故,我得到以下输出:
10 was added to the integers heap! 3 was added to the Heap Currect counter is:1 Currect counter is:2 2 was added to the Heap Currect counter is:-2 Currect counter is:-1
下次我使用该函数时,是否有任何理由使计数器变为 -2?
如果有帮助,class 的其余部分就是这样定义的:
template <>
class Heap<int> {
public:
Heap (int x) {
arr[0]=x;
arr_counter=1;
cout<<this->arr[0]<< " was added to the integers heap!"<<endl;
}
//...some other functions
private:
int arr[10];
int arr_counter;
};
Heap operator+=(int newHeap)
应该是 Heap& operator+=(int newHeap)
并且需要 return *this
才能工作。 我认为代码 as-is 无法编译。 打开更高级别的编译器警告是个好习惯。
根据您发布的不完整代码,它可能是未初始化的变量问题,也可能是对象内存损坏(您是否在任何地方 memset 0?)