簡體   English   中英

C ++加法運算符

[英]C++ Addition Operator

這是我以格式(HH,MM,SS)一起添加2個Duration對象的方法。

    inline ostream& operator<<(ostream& ostr, const Duration& d){
      return ostr << d.getHours() << ':' << d.getMinutes() << ':' << d.getSeconds();
    }

    Duration operator+ (const Duration& x, const Duration& y){
        if ( (x.getMinutes() + y.getMinutes() >= 60) && (x.getSeconds() + y.getSeconds() >= 60) ){
           Duration z( (x.getHours() + y.getHours() + 1), (x.getMinutes() + y.getMinutes() + 1 - 60), (x.getSeconds() + y.getSeconds() - 60) );
           return z;
        }
        else if (x.getSeconds() + y.getSeconds() >= 60){
           Duration z( (x.getHours() + y.getHours()), (x.getMinutes() + y.getMinutes() + 1), (x.getSeconds() + y.getSeconds() - 60) );
           return z;
        }
        else if (x.getMinutes() + y.getMinutes() >= 60){
           Duration z( (x.getHours() + y.getHours() + 1), (x.getMinutes() + y.getMinutes() - 60), (x.getSeconds() + y.getSeconds()) );
           return z;
        }
        else{
            Duration z( (x.getHours() + y.getHours()), (x.getMinutes() + y.getMinutes()), (x.getSeconds() + y.getSeconds()) );
            return z;
        }
    }

在我的主要方法中,我有:

  Duration dTest4 (01,25,15);
  Duration result = dTest4+dTest4;
  cout << result << endl;

不幸的是,當我運行該程序時,我收到此錯誤:

  error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Duration const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABVDuration@@@Z) referenced in function _wmain 1>C:\Users\...exe : fatal error LNK1120: 1 unresolved externals

我希望能夠在單個實體中一起添加兩次。 IE瀏覽器。 小時在一起,然后是分鍾,然后是秒。 因此,當兩組分鍾超過一小時的60分鍾時,處理if-else ...

任何幫助,將不勝感激。

問題出在這里: cout << result << endl; 您尚未定義std::ostream& operator<<的重載版本,用於將Duration對象寫入ostream。 這樣的事情應該這樣做:

std::ostream& operator<<(std::ostream& os, const Duration& rhs)
{ 
os << "Hours: <" << hours_ << ">, ";  
os << "Minutes: <" << minutes_ << ">, "; 
os << "Seconds: <" << seconds_ << ">"; 
return os; 
}

我猜測流插入器是在Duration類的源文件中定義的,而不是在頭文件中定義的; 這將解釋未定義的引用,因為它是內聯的。 如果是這種情況,請將內聯定義移動到標題中。

有一個問題在另外,太:如果兩個分秒溢出會發生什么? 第一個if語句將捕獲分鍾溢出並返回一個Duration對象,其秒超出范圍。 創建新對象可能更簡單,不考慮溢出,然后檢查溢出的秒數,並在必要時處理它,然后檢查溢出的分鍾數,並在必要時處理它。 現在您知道為什么大多數日期/時間庫使用整數類型來存儲超過時期的秒數(或其他),而不是像這樣分解細節。

您需要為<<運算符創建方法。 目前,cout無法解析你的持續時間。

問題出在這條線上
cout << result << endl;

你試圖在一個對象上使用<<運算符,而你只重載了+運算符try: cout << result.getHours() << endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM