运算符重载添加两个对象错误

Operator overloading adding two objects error

本文关键字:两个 对象 错误 重载 添加 运算符      更新时间:2023-10-16

我不知道为什么这个代码应该工作,但告诉我如果我想添加两个对象该怎么办在一起请当你试图回答时,请更多地使用特定于角落的

很抱歉我英语不好,我是印度人,这是我的密码。

#include<iostream>
using namespace std;
class time
{
private:
    int sec;
    int mint;
    int hours;
public:
    int Inputsec;
    int Inputmint;
    int Inputhours;
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours){};
time operator+(time Inputobj)
{
    time blah (sec+Inputsec,mint+Inputmint,hours+Inputhours);
    return blah;
}
void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};
int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}

代码运行良好,但它给我的输出很糟糕。我的错误在哪里?

您的加法运算符正在使用单元化的成员InputsecInputmintInputhours变量。它应该是这样的:

time operator+(time Inputobj)
{
    return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
}

time operator+(time Inputobj)
{
    InputObj.sec += sec;
    InputObj.mint += mint;
    InputObj.hours += hours;
    return InputObj;
}

或者,更好的是,实现time& operator+=(const time& rhs);并将其用于非成员添加运算符:

time operator+(time lhs, const time& rhs)
{
  return lhs += rhs;
}

您有两组成员变量表示相同的内容。您不需要这种复制。

最后一句话:在标题<ctime>中有一种叫做std::time的东西。拥有一个名为timeusing namespace std的类是在自讨苦吃。如果可能的话,你应该两者都避免(避免第二种肯定是可能的)。

您应该至少按如下方式重写operator+

time operator+(time Inputobj)
{
    time blah time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
    return blah;
}

我还认为你应该使用%运算符来获得正确的时间结果:

time operator+(time Inputobj){
    int s = (sec+InputObj.sec) % 60;
    int m = (sec+InputObj.sec) / 60 + (mint+InputObj.mint) % 60;
    int h = (mint+InputObj.mint) / 60 + (hours+InputObj.hours) % 24;
    return time(s,m,h);
}

您的运算符重载函数正在使用未初始化的变量。初始化构造函数中的变量inputsec, inputmint, Inputhours

此外,试试这个:

time operator+ (time Inputobj)
{
   time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
   return blah;
}

您的错误是您的publics成员与参数构造函数具有相同的名称,这些成员是统一的。试试这个:

#include <iostream>
using namespace std;
class time
{
private:
    int sec;
    int mint;
    int hours;
public:
time(int Inputsec, int Inputmint, int Inputhours):sec(Inputsec), mint(Inputmint), hours(Inputhours)
{
};
time operator+(time Inputobj)
{
    time blah (sec+Inputobj.sec, mint+Inputobj.mint, hours+Inputobj.hours);
    return blah;
}
void DisplayCurrentTime()
{
    cout << "The Current Time Is"<<endl<< hours<<" hours"<<endl<<mint<<"minutes"<<endl<<sec<<"seconds"<<endl;
}
};
int main()
{
time now(11,13,3);
time after(13,31,11);
time then(now+after);
then.DisplayCurrentTime();
}