2012-11-12 91 views
0

|55|error: no match for 'operator<<' in 'std::cout << DetermineElapsedTime(((const MyTime*)(& tm)), ((const MyTime*)(& tm2)))'|如何解決'std :: cout'錯誤中'不匹配'operator <<'的問題?

我意識到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 ..有點。

回答

3

MyTime是一個結構體。超負荷< <運營商對這種類型

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

我還沒有學到這一點,但在時間的功能呢? – user1781382

+0

不,你可以在main和elapse函數之外定義它。它將匹配MyTime類型並描述如何在ostream中使用MyTime類型(cout是一個ostream)。 – gvd

+0

謝謝。這有幫助,一開始不明白,但其他海報幫助我。 – user1781382

1

您必須聲明流運算符爲您MyTime結構:

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

如果你不能改變結構,然後宣佈免費運營:

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

我不應該改變結構 – user1781382

+0

即使你可以改變'MyTime',爲什麼你會讓它成爲朋友?無論如何,所有f MyTime的成員都是公開的。 –

+0

明白了。謝謝。 – user1781382

相關問題