如何使用堆分配进行运算符++重载

How to do operator++ overloading with heap allocation

本文关键字:运算符 重载 何使用 分配      更新时间:2023-10-16

我想重载++运算符,但它不起作用。我在书中找到的示例使用了堆栈内存分配,我尝试通过堆内存分配来实现。它没有崩溃,但也没有递增。

我尝试返回指针,进行引用,各种我还不太理解的东西,但没有任何实际效果。

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