我想重载++运算符,但是它不起作用。我在书中找到的示例正在使用已使用的堆栈内存分配,并尝试通过堆内存分配来实现。它没有崩溃,但也没有增加。
我尝试返回指针,进行引用,各种我还不太了解的东西,但实际上没有任何作用。
#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循环开始时进行迭代。对此,我们也提供了帮助。
答案 0 :(得分:5)
您已成为operator precedence的受害者。表达式*pointer++
取消引用指针,返回该引用并递增指针,而不是值。等效于*(pointer++)
。
解决方案是添加一对括号:(*pointer)++
。
不要使用new
,std::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;
}