视觉上的一元操作员在C 中超载特殊情况
visual unary operator overloading special case in c++
我的成功完全超载了Unary ++,--
Postfix/prefix Operator,而我的代码正常运行,但是当使用(++obj)++
语句时,它会返回意外结果
这是代码
class ABC
{
public:
ABC(int k)
{
i = k;
}
ABC operator++(int )
{
return ABC(i++);
}
ABC operator++()
{
return ABC(++i);
}
int getInt()
{
return i;
}
private:
int i;
};
int main()
{
ABC obj(5);
cout<< obj.getInt() <<endl; //this will print 5
obj++;
cout<< obj.getInt() <<endl; //this will print 6 - success
++obj;
cout<< obj.getInt() <<endl; //this will print 7 - success
cout<< (++obj)++.getInt() <<endl; //this will print 8 - success
cout<< obj.getInt() <<endl; //this will print 8 - fail (should print 9)
return 1;
}
有任何解决方案或原因???
预先注册应返回 ABC&
,而不是 ABC
,通常。
您会注意到,这将使您的代码无法编译。固定相对容易(不要创建新的ABC
,只需编辑现有的值,然后返回*this
)。
我发现最好以插入后实施插入后。
ABC operator++(int )
{
ABC result(*this);
++*this; // thus post-increment has identical side effects to post-increment
return result; // but return value from *before* increment
}
ABC& operator++()
{
++i; // Or whatever pre-increment should do in your class
return *this;
}
相关文章:
- 如何在音频处理中使用超能力时间拉伸类
- 我的超类中的模板问题与结构定义
- 在具有 MPI 的超立方体中广播
- 在 c++ 中调用超构造函数之前做一些事情
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- C++为API中定义的结构创建超类
- 确保指向超类的指针指向c++中某个子类的对象
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- C++:从类型索引中获取超类类型索引
- C++11 中对超载'ref(Select::Expressions::Code&)'的调用模棱两可
- 如何将项目放入具有模板化超类类型的向量中
- QT 中的串行通信超时与 Arduino
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 如何将基类方法超载作为参数传递到C 中的模板类
- 班级(Arduino)中的超载方法
- 在C 中的超载运算符中使用局部变量
- 尝试在构造函数中超限时间
- 多态性(C )的派生类中的超载函数
- 更改所有子类中超类变量的值
- 如何在C++中超类某些数据结构