如何修复“不匹配'运算符<<'在'std :: cout'错误?

时间:2012-11-12 08:17:58

标签: c++ compiler-errors output

|55|error: no match for 'operator<<' in 'std::cout << DetermineElapsedTime(((const MyTime*)(& tm)), ((const MyTime*)(& tm2)))'|

我意识到cout不理解如何正确输出。但是,此时我也不会。

这是我的代码。问题一直接近底部。

#include <iostream>
#include <cstdlib>
#include <cstring>


using namespace std;
struct MyTime { int hours, minutes, seconds; };
MyTime DetermineElapsedTime(const MyTime *t1, const MyTime *t2);

const int hourSeconds = 3600;
const int minSeconds = 60;
const int dayHours = 24;

MyTime DetermineElapsedTime(const MyTime *t1, const MyTime *t2)
{
    long hourDiff = ((t2->hours * hourSeconds) - (t1->hours * hourSeconds));
    int timeHour = hourDiff / hourSeconds;
    long minDiff = ((t2->minutes * minSeconds) - (t1->minutes * minSeconds));
    int timeMin = minDiff / minSeconds;
    int timeSec = (t2->seconds - t1 -> seconds);
    MyTime time;
    time.hours = timeHour;
    time.minutes = timeMin;
    time.seconds = timeSec;
    return time;
}


main(void)
{
    char delim1, delim2;
    MyTime tm, tm2;
    cout << "Input two formats for the time. Separate each with a space. Ex: hr:min:sec\n";
    cin >> tm.hours >> delim1 >> tm.minutes >> delim2 >> tm.seconds;
    cin >> tm2.hours >> delim1 >> tm2.minutes >> delim2 >> tm2.seconds;

    if (tm2.hours <= tm.hours && tm2.minutes <= tm.minutes && tm2.seconds <= tm.seconds)
        {
            tm2.hours += dayHours;
        }
    cout << DetermineElapsedTime(&tm, &tm2); // Problem is here

    return 0;

}

此外,如果需要,有关如何输出时间01:01:01的任何提示?我知道setfill ..有点。

2 个答案:

答案 0 :(得分:3)

MyTime是一个结构。重载&lt;&lt;此类型的运算符

std::ostream& operator<< (ostream& os, const MyTime& m) {
       os << m.hours << ":" << m.minutes << ":" << m.seconds;
       return os;
}  

答案 1 :(得分:1)

您必须为MyTime结构声明流操作符:

struct MyTime
{
    int hours, minutes, seconds;
    friend ostream& operator<<(ostream& sm)
    {
         sm << "hours: "<<hours<<" seconds: "<<seconds<<" minutes: "<<minutes;
         return sm;
    }
};

如果你不能改变struct然后声明自由运算符:

ostream& operator<<(ostream& sm, const MyTime& my_time)
{
     sm << "hours: "<<my_time.hours<<" seconds: "<<my_time.seconds<<" minutes: "<<my_time.minutes;
     return sm;
}