此上下文中的c++错误和重载运算符+

c++ error within this context and overloading operator+

本文关键字:重载 运算符 错误 c++ 上下文      更新时间:2023-10-16

我正在处理这个赋值,但在编码时遇到了问题。函数运算符+是上下文中的错误。此外,我的全部或部分函数是否适用于此任务?如果没有,请指出应该纠正的

该程序创建了一个NumDays类,使用两个int成员变量来表示一个人工作的天数和小时数(一天总共只有8小时)。该程序要求使用运算符+以及增量(++)和减量(--)的后缀和前缀运算符。例如:

8小时=1天

12小时=1天4小时

16小时=2天

运算符+函数必须调用私有成员函数才能转换为正确的天数和小时数。

应该调用私有成员函数以转换为正确的天数和小时数。

如果天数和小时数都已为0,则递减运算符不应对对象执行任何操作。如果对象已更改,则应调用私有成员函数以转换为正确的天数和小时数。

编辑

我的函数(包括运算符+)正在工作,但当我同时添加一个两个算符+中返回什么?

编辑2

最后,operator+正在工作。将第一个.getDays()替换为这个->day_hour+a.day_hour有效。

这是我到目前为止的程序:

#include <iostream>
using namespace std;
class NumDays
{
private:
    int day_hour;
public:
    NumDays(int, int);
    NumDays(int);
    void setTime(int, int);
    int getDays() const;
    int getHours() const;
    NumDays operator+(const NumDays&);
    NumDays operator++();
    NumDays operator++(int);
    NumDays operator--();
    NumDays operator--(int);
};
NumDays::NumDays(int days, int hours)
{
setTime(days, hours);
}
NumDays::NumDays(int hours)
{
day_hour=hours;
}
void NumDays::setTime(int days, int hours)
{
day_hour=8 *days+hours;
}
int NumDays::getDays() const
{
return day_hour/8;
}
int NumDays::getHours() const
{
return day_hour%8;
}
NumDays NumDays::operator+(const NumDays& a)
{
return NumDays(a.getDays()+ a.getHours());
}
NumDays NumDays::operator++()
{
day_hour++;
return *this;
}
NumDays NumDays::operator++(int)
{
NumDays time=*this;
day_hour++;
return time;
}
NumDays NumDays::operator--()
{
day_hour--;
return *this;
}
NumDays NumDays::operator--(int)
{
NumDays time=*this;
day_hour--;
return time;
}
int main()
{
NumDays one(25);
NumDays two(16);
NumDays three(0);
cout<<endl<<one.getDays()<<" days and "<<one.getHours()<<" hours."<<endl;
cout<<two.getDays()<<" days and "<<two.getHours()<<" hours."<<endl;
three=one+two;
cout<<three.getDays()<<" days and "<<three.getHours()<<" hours."<<endl;
cout<<endl;
for(int i=0; i<3; i++)
{
    one=++two;
    cout<<one.getDays()<<" days and "<<one.getHours()<<" hours."<<endl;
}
cout<<endl;
for(int i=0; i<3; i++)
{
    one=two++;
    cout<<one.getDays()<<" days and "<<one.getHours()<<" hours."<<endl;
}
cout<<endl;
for(int i=0; i<3; i++)
{
two=--one;
cout<<two.getDays()<<" days and "<<two.getHours()<<" hours."<<endl;
}
cout<<endl;
for(int i=0; i<3; i++)
{
two=one--;
cout<<two.getDays()<<" days and "<<two.getHours()<<" hours."<<endl;
}
return 0;
}

的声明

NumDays operator+();

与的定义不一致

NumDays NumDays::operator+(NumDays a, NumDays b){...}

如果您想让operator+成为成员函数,则必须将其声明为

NumDays operator+(const NumDays& rhs); // you invoke it on current instance

然而,最好不要将二进制运算符声明为成员函数,而是将其声明为friends,例如:

friend NumDays operator+(const NumDays& lhs, const NumDays& rhs);

声明它们的方式意味着您正试图在当前实例上调用它们(在这种情况下,您只需要一个参数,而不需要两个)。

有关优秀指南,请参阅操作员过载。