gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:53:09 26 4
gpt4 key购买 nike

我不知道为什么这段代码应该有效,但告诉我如果我想添加两个对象该怎么做一起。请。当你试图回答时,请更具体一些菜鸟

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

#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();
}

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

最佳答案

您的加法运算符正在使用未初始化的成员 Inputsec , InputmintInputhours变量。它应该看起来像这样:

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;
}

您有两组成员变量代表同一事物。你不需要这个拷贝。

最后一点:有一个东西叫做 std::time在标题中 <ctime> .有一个名为 time 的类(class), 和 using namespace std是自找麻烦。如果可能,您应该避免这两种情况(避免第二种情况绝对是可能的)。

关于c++ - 运算符重载添加两个对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17274913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com