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

Noo*_*mer 1 c++ operator-overloading object

我不知道为什么这个代码应该工作,但如果我想要将两个对象一起添加,请告诉我该怎么做.请.当你试图回答时请更专注于菜鸟

抱歉我的英语不好,我是印度人,这是我的代码.

#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();
}
Run Code Online (Sandbox Code Playgroud)

代码工作正常,但它给了我可怕的输出.我的错误在哪里?

jua*_*nza 5

你除了运营商正在使用unitinitialized成员Inputsec,InputmintInputhours变量.它应该如下所示:

time operator+(time Inputobj)
{
    return time(sec+InputObj.sec, mint+InputObj.mint, hours+InputObj.hours);
}
Run Code Online (Sandbox Code Playgroud)

要么

time operator+(time Inputobj)
{
    InputObj.sec += sec;
    InputObj.mint += mint;
    InputObj.hours += hours;
    return InputObj;
}
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,time& operator+=(const time& rhs);在非成员添加运算符中实现和使用它:

time operator+(time lhs, const time& rhs)
{
  return lhs += rhs;
}
Run Code Online (Sandbox Code Playgroud)

你有两组代表同一件事的成员变量.您不需要这种重复.

最后一句话:std::time标题中有一些内容<ctime>.有一个课程time,并using namespace std要求麻烦.如果可能的话,你应该避免两者(避免第二个肯定是可能的).