如何使用堆分配进行运算符++重载
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)++
。
不要使用 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;
}
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板