gpt4 book ai didi

c++ - TimeUnit 类中的 Add 方法的问题

转载 作者:行者123 更新时间:2023-11-28 03:22:04 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class TimeUnit
{
public:
TimeUnit(int m, int s)
{
this -> minutes = m;
this -> seconds = s;
}

string ToString()
{
ostringstream o;
o << minutes << " minutes and " << seconds << " seconds." << endl;

return o.str();
}

void Simplify()
{
if (seconds >= 60)
{
minutes += seconds / 60;
seconds %= 60;
}
}

TimeUnit Add(TimeUnit t2)
{
TimeUnit t3;

t3.seconds = seconds + t2.seconds;

if(t3.seconds >= 60)
{
t2.minutes += 1;
t3.seconds -= 60;
}

t3.minutes = minutes + t2.minutes;

return t3;
}

private:
int minutes;
int seconds;

};

int main(){

cout << "Hello World!" << endl;

TimeUnit t1(2,30);
cout << "Time1:" << t1.ToString() << endl;

TimeUnit t2(3,119);
cout << "Time2:" << t2.ToString();
t2.Simplify();
cout << " simplified: " << t2.ToString() << endl;

cout << "Added: " << t1.Add(t2).ToString() << endl;
//cout << " t1 + t2: " << (t1 + t2).ToString() << endl;

/*cout << "Postfix increment: " << (t2++).ToString() << endl;
cout << "After Postfix increment: " << t2.ToString() << endl;

++t2;
cout << "Prefix increment: " << t2.ToString() << endl;*/

}

我的 Add 方法有问题。 Xcode 给我这个错误:“TimeUnit 初始化没有匹配的构造函数”

有人可以告诉我我做错了什么吗?我确实已经尝试了所有我知道如何做的事情,但我什至无法使用这种方法进行编译。

这是我教授的指示:

The TimeUnit class should be able to hold a time consisting of Minutes and Seconds. It should have the following methods:

A constructor that takes a Minute and Second as parameters ToString() - Should return the string equivilant of the time. "M minutes S seconds." Test1 Simplify() - This method should take the time and simplify it. If the seconds is 60 seconds or over, it should reduce the seconds down to below 60 and increase the minutes. For example, 2 Min 121 seconds should become 4 minutes 1 second. Test2 Add(t2) - Should return a new time that is the simplified addition of the two times Test3 operator + should do the same thing as Add Test4 pre and postfix ++: should increase the time by 1 second and simplify Test5

最佳答案

在您的 TimeUnit::Add 函数中,您尝试使用默认构造函数初始化 t3。但是,您的 TimeUnit 没有:

TimeUnit Add(TimeUnit t2)
{
TimeUnit t3; ///<<<---- here
///.....
}

尝试将 TimeUnit::Add 更新为这种方式:

TimeUnit Add(const TimeUnit& t2)
{
return TimeUnit(this->minutes+t2.minutes, this->seconds+t2.seconds);
}

关于c++ - TimeUnit 类中的 Add 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15150356/

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