下次使用该函数将犯错



首先,我对标题感到抱歉,无法清楚地使用一个句子来解释。

我正在创建一个具有数组和计数器的对象,以计算数组中有多少个元素,但是每当我添加一个数字时,计数器都会以某种方式失去其值。我正在使用以下功能来将元素添加到数组中:

    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?

如果有帮助,则其余的课程是这样定义的:

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),需要返回 *this才能工作。我不认为代码编译。打开更高级别的编译器警告是一个好习惯。

基于您发布的不完整代码,它可以是一个非初始化的变量问题,也可以是对象内存损坏(您在任何地方Memset 0?)

最新更新