#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 的初始化”
有人可以告诉我我做错了什么吗?我已经尝试了所有我知道该怎么做的事情,但我什至无法用这种方法编译它。
以下是我教授的指示:
TimeUnit 类应该能够保存由分和秒组成的时间。它应该有以下方法:
以 Minute 和 Second 作为参数的构造函数 ToString() - 应该返回时间的等值字符串。“M分S秒。” Test1 Simplify() - 这个方法应该花费时间并简化它。如果秒数为 60 秒或以上,则应将秒数减少到 60 以下并增加分钟数。例如,2 分 121 秒应变为 4 分 1 秒。Test2 Add(t2) - 应该返回一个新时间,即两次 Test3 运算符 + 的简化相加应该与 Add Test4 pre 和 postfix ++ 做同样的事情:应该将时间增加 1 秒并简化 Test5