尝试重载 c++ 中的后增量运算符,但答案与预期不符
Tryiing to overload the post increment operator in c++ in but the answer is not as expected
#include <iostream>
using namespace std;
class B{
int temp1;
public :
void disp()
{
cout <<temp1;
}
void setA(int a)
{
temp1=a;
}
void operator ++(int)
{
temp1+=5;
}
void cal()
{
temp1 ++;
}
};
int main()
{
B b;
b.setA(10);
b.cal();
b.disp();
return 0;
}
我最近了解到运算符重载,所以玩代码.....所以这里的预期答案是 15,但它显示为 11。为什么我的重载运算符不起作用...特别是这段代码有什么问题,因为这部分似乎存在逻辑错误:
void operator ++(int)
{
temp1+=5;
}
void cal()
{
temp1 ++;
}
请注意,
您重载了类 B
的 ++
运算符。cal
方法使用++
成员temp1
递增,这是一个int
,而不是一个B
- 因此 - 它正常增加,从 10 增加到 11。
如果你在main
函数中做b++
,你就会得到你所期望的。注意 ++
应该返回递增对象的先前值,如果您希望与大多数人的期望保持共形,因此
something = b++; //something should probably be a B.
会工作。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 欧拉项目#8答案是大以获得有效答案
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 尝试重载 c++ 中的后增量运算符,但答案与预期不符
- 计算函数中的模给出了与直接使用%运算符不同的答案
- 我没有得到我期望使用按位not运算符的答案.我很感激你的帮助