简体   繁体   中英

How to do operator++ overloading with heap allocation

I want to overload the ++ operator but it isn't working. The example I found in the book I'm using used stack memory allocation and I tried to do it through heap memory allocation. It isn't crashing but it isn't incrementing either.

I tried returning the pointer, making a reference, all sorts of stuff that I don't quite understand yet and nothing really worked.

#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;
}

Actual:

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

Also, my test to see if the response was not either Y or N stops the program when true instead of iterating at the beginning of the while loop. Help on that is also appreciated.

You've fallen victim to operator precedence . The expression *pointer++ dereferences the pointer, returns that reference and increments the pointer, not the value. It's equivalent to *(pointer++) .

The solution is to add a pair of parentheses: (*pointer)++ .

Don't use new , std::unique_ptr is the correct way to handle dynamic memory.

Also you overloaded the prefix operator, you probably wanted postfix. Both operators should look something like this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM