【问题标题】:Problems with Add method in TimeUnit classTimeUnit 类中的 Add 方法的问题
【发布时间】:2013-02-15 12:27:03
【问题描述】:
#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 类应该能够保存由 Minutes 组成的时间 和秒。它应该有以下方法:

一个以 Minute 和 Second 作为参数的构造函数 ToString() - 应该返回时间等价的字符串。 “M分S秒。” Test1 Simplify() - 这个方法需要时间和 简化它。如果秒数为 60 秒或以上,则应减少 将秒数降至 60 以下并增加分钟数。例如,2 最小 121 秒应变为 4 分 1 秒。测试2添加(t2) - 应该返回一个新时间,即两者的简化相加 次 Test3 运算符 + 应该与 Add Test4 pre 和 postfix ++:应该将时间增加 1 秒并简化 Test5

【问题讨论】:

    标签: c++


    【解决方案1】:

    在您的 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);
    }
    

    【讨论】:

    • 这正是我需要的,谢谢!我现在只需要简化它。
    【解决方案2】:

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

    【讨论】:

    • 我很抱歉没有早点发布说明,但现在已经发布了。我不能再创建任何构造函数了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多