c++ - 如何在 C++ 中为具有 2 个变量的对象重载增量运算符?
问题描述
所以我一直遇到运算符重载的问题。所以我有一个程序,它有一个名为Weight的对象,它有 2 个属性,磅和盎司。我找出了所有其他运算符,但增量一给我带来了麻烦。我试图这样做,但由于某种原因,它不想工作。
以下是头文件中的声明(包括 2 个变量):
void operator++();
void operator--();
private:
int pounds;
int ounces;
和成员函数:
void Weight::operator++() {
pounds + 1;
ounces + 15;
}
void Weight::operator--() {
pounds - 1;
ounces - 15;
}
什么都有帮助!
解决方案
发布的代码存在两个问题。
Weight
当您增加或减少对象时,不清楚应该发生这种情况。它的价值应该上升/下降一盎司或一磅。表达式
pounds + 1
,ounces + 15
等不会改变对象中的任何内容。他们计算一个值,然后丢弃结果。
假设 inrement 运算符将值更改一盎司,您必须使用:
void Weight::operator++() {
ounces++;
// If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
if ( ounces == 16 )
{
pounds++;
ounces = 0;
}
// That can also be achieved by using.
// pounds += (ounces / 16);
// ounces = (ounces % 16);
}
此外,重载++
运算符的规范做法是返回对对象的引用。因此,您应该使用:
Weight& Weight::operator++() {
ounces++;
// If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
if ( ounces == 16 )
{
pounds++;
ounces = 0;
}
// That can also be achieved by using.
// pounds += (ounces / 16);
// ounces = (ounces % 16);
return *this;
}
您必须operator--
类似地更新该功能。
推荐阅读
- python - 根据列表中出现的字符串对数据框行进行分类
- java - 如何打印最长的三个字符串?
- r - Weighted mean of a group, where weight is from another group
- android - React Native:来自 uri 的图像未在 Android 上使用字符串插值来呈现以移交令牌
- java - 流分组列表
- >
- sharepoint - 如何为 Sharepoint2019 的 Windows 身份验证创建 Custom.aspx
- c# - 从sql查询中输出删除的变量在c#中不起作用
- elasticsearch - 在elasticsearch中通过部分匹配搜索字符串数组
- arrays - 在c中创建动态结构数组
- arrays - Swift 固定大小的数组在每次追加后都会改变大小