首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TimeUnit类中添加方法的问题

TimeUnit类中添加方法的问题
EN

Stack Overflow用户
提问于 2013-03-01 04:12:33
回答 2查看 167关注 0票数 0
代码语言:javascript
复制
#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;*/

}

我的添加方法有问题。Xcode给出了以下错误:“没有匹配的TimeUnit初始化构造函数”

有人能告诉我我做错了什么吗?我已经尝试了所有我知道如何做的事情,但我甚至无法让它用这个方法编译。

以下是我的教授的说明:

TimeUnit类应该能够保存由分钟和秒组成的时间。它应该有以下方法: 以一分钟和秒作为参数ToString() -的构造函数应该返回时间相等的字符串。"M分S秒“Test1 Simplify() -这个方法应该花时间简化它。如果秒数为60秒或以上,则应将秒数降至低于60秒,并增加分钟数。例如,2Min 121秒应该变成4分1秒。Test2 Add(t2) -应该返回一个新的时间,即简化Test3运算符+应该做的与添加Test4 pre和后缀++相同的添加:应该增加1秒的时间并简化Test5

EN

回答 2

Stack Overflow用户

发布于 2013-03-01 04:18:00

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

代码语言:javascript
复制
TimeUnit Add(TimeUnit t2)
{
   TimeUnit t3;   ///<<<---- here
   ///.....
}

尝试以这种方式更新TimeUnit::Add

代码语言:javascript
复制
TimeUnit Add(const TimeUnit& t2)
{
   return TimeUnit(this->minutes+t2.minutes, this->seconds+t2.seconds);
}
票数 2
EN

Stack Overflow用户

发布于 2013-03-01 04:16:04

具体的问题是没有定义TimeUnit::TimeUnit(),只有TimeUnit(const int &m, const int &s)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15150356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档