簡體   English   中英

如何使用堆分配進行Operator ++重載

[英]How to do operator++ overloading with heap allocation

我想重載++運算符,但是它不起作用。 我在書中找到的示例正在使用已使用的堆棧內存分配,並嘗試通過堆內存分配來實現。 它沒有崩潰,但也沒有增加。

我嘗試返回指針,進行引用,各種我還不太了解的東西,但實際上沒有任何作用。

#include <iostream>

using namespace std;

class MyObject{
public:
  MyObject(int initVal = 0):value(initVal){cout << "Constructor called..." << endl;}
  ~MyObject(){cout << "Destructor called..." << endl;}
  const MyObject& operator++();
  int getValue(){return value;}
private:
  int value = 0;

};

int main(){
  int initVal = 0;
  char done = 'N';

  cout << "initVal?" << endl;
  cin >> initVal;
  MyObject *obj = new MyObject(initVal);
  while(done == 'N'){
    cout << "Current value of obj :" << obj->getValue() << ". Want to stop? (Y/N)" << endl;
    cin >> done;
    //cout << "value of done :" << done << endl;
    //cin.get();
    if(done != 'Y' || done != 'N'){
      continue;
    }
    *obj++;
  }
  cout << "";
  cin.get();
}

const MyObject& MyObject::operator++(){
  cout << "OVERLOADER CALLED val:" << value << endl;
  value++;
  return *this;
}

實際:

initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)

Expected:initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :11. Want to stop? (Y/N)
N
Current value of obj :12. Want to stop? (Y/N)
N
Current value of obj :13. Want to stop? (Y/N)
Y

此外,我的測試(如果響應不是Y還是N)將在true時停止程序,而不是在while循環開始時進行迭代。 對此也有所幫助。

您已經成為運算符優先級的犧牲品。 表達式*pointer++取消引用該指針,返回該引用並遞增該指針,而不是值。 等效於*(pointer++)

解決方案是添加一對括號: (*pointer)++

不要使用newstd::unique_ptr是處理動態內存的正確方法。

另外,您重載了前綴運算符,您可能需要后綴。 兩家運營商應該看起來像這樣:

MyObject MyObjects::operator++(int)//Post-fix accepts unused int argument
{
    MyObject copy{*this};
    ++*this; // Use prefix++ to avoid redundant code.
    return copy;
}

MyObject& MyObjects::operator++()
{
    //Put incrementing logic here
    ++this->value;
    return *this;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM