2015-02-24 83 views
2

我看了一下LNK2019很多帖子,但無法解決此錯誤。C++ LNK2019解析的外部符號

這裏是我的代碼:

time.h中:

#ifndef PROJECT2_TIME_H 
#define PROJECT2_TIME_H 

#include<iostream> 
using std::ostream; 

namespace Project2 
{ 
class Time 
{ 
    friend Time& operator+=(const Time& lhs, const Time& rhs); 
    friend ostream& operator<<(ostream& os, const Time& rhs); 
public: 
    static const unsigned secondsInOneHour = 3600; 
    static const unsigned secondsInOneMinute = 60; 
    Time(unsigned hours, unsigned minutes, unsigned seconds); 
    unsigned getTotalTimeAsSeconds() const; 
private: 
    unsigned seconds; 
}; 

Time& operator+=(const Time& lhs, const Time& rhs); 
ostream& operator<<(ostream& os, const Time& rhs); 

} 

#endif 

Time.cpp:

#include "Time.h" 


Project2::Time::Time(unsigned hours, unsigned minutes, unsigned seconds) 
{ 
    this->seconds = hours*secondsInOneHour + minutes*secondsInOneMinute + seconds; 
} 

unsigned 
Project2::Time::getTotalTimeAsSeconds() const 
{ 
return this->seconds; 
} 


Project2::Time& 
Project2::operator+=(const Time& lhs, const Time& rhs) 
{ 
Time& tempTime(unsigned hours, unsigned minutes, unsigned seconds); 
unsigned lhsHours = lhs.seconds/Time::secondsInOneHour; 
unsigned lhsMinutes = (lhs.seconds/60) % 60; 
unsigned lhsSeconds = (lhs.seconds/60/60) % 60; 
unsigned rhsHours = rhs.seconds/Time::secondsInOneHour; 
unsigned rhsMinutes = (rhs.seconds/60) % 60; 
unsigned rhsSeconds = (rhs.seconds/60/60) % 60; 
return tempTime(lhsHours + rhsHours, lhsMinutes + rhsMinutes, lhsSeconds + rhsSeconds); 
} 

ostream& 
Project2::operator<<(ostream& os, const Time& rhs) 
{ 
unsigned rhsHours = rhs.seconds/Time::secondsInOneHour; 
unsigned rhsMinutes = (rhs.seconds/60) % 60; 
unsigned rhsSeconds = (rhs.seconds/60/60) % 60; 
os << rhsHours << "h:" << rhsMinutes << "m:" << rhsSeconds << "s"; 
return os; 
} 

的main.cpp中簡單的創建時間對象,並使用重載操作符,似乎不會有問題(提供這些代碼本身就很好) 。

我試圖刪除「&」背後的「時代」的象徵,而我得到了同樣的錯誤。

這裏是錯誤消息:

錯誤1個錯誤LNK2019:無法解析的外部符號 「類Project2的時間:: __cdecl & tempTime(無符號整數,無符號整型,無符號整型)」(tempTime @@ @ YAAAVTime Project2的@@ @ III Z)函數 「類Project2的::時間& __cdecl Project2的::運算+ =(類Project2的::時間常量&,類Project2的::時間常量&)」(?? YProject2 @引用@ YAAAVTime @ 0 @ ABV10 @ 0 @ Z)C:\用戶\宙-GWEI \文件\視覺工作室2013 \項目\ C++ III_Project2_GW \ C++ III_Project2_GW \ Time.obj C++ III_Project2_GW

+0

哪個符號無法鏈接?您需要提供實際的錯誤消息。 – Gadi 2015-02-24 06:05:41

回答

0

Time& tempTime(unsigned hours, unsigned minutes, unsigned seconds);聲明名稱爲tempTimereturn tempTime(lhsHours + rhsHours, lhsMinutes + rhsMinutes, lhsSeconds + rhsSeconds);的函數調用該函數。由於函數在任何地方都沒有實現,所以會出現鏈接器錯誤。

由於 operator +=據推測應該返回到它,你應該通過 this修改對象的成員變量,而不是創建一個新 Time調用對象的引用,並返回 *this 編輯:任何理智的實施operator +=將修改的左手側的操作數,而不是創建一個新的對象。我建議你重新考慮你的操作員應該如何工作。

+0

謝謝!我試圖修改Time&lhs並將其返回,錯誤消失了。 – 2015-02-24 06:29:04

+0

@aureus:太好了!請接受這個答案,因爲它解決了你的問題(除了給我聲望點外,這會阻止其他人認爲這個問題仍然需要回答,並且花費時間不必要)。 – 2015-02-24 06:38:46

+0

我嘗試過,但我需要15的聲譽給予好評... – 2015-02-24 08:57:00

相關問題