我已阅读很多关于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只是简单地创建Time对象并使用重载的运算符,似乎不存在问题(提供这些代码本身就是好的)。
我试图删除“&amp;”在所有“时间”符号后面,我得到了同样的错误。
以下是错误消息:
错误1错误LNK2019:未解析的外部符号“类Project2 :: Time&amp; __cdecl tempTime(unsigned int,unsigned int,unsigned int)”(?tempTime @@ YAAAVTime @ Project2 @@ III @ Z)在函数中引用“ class Project2 :: Time&amp; __cdecl Project2 :: operator + =(class project2 :: Time const&amp;,class Project2 :: Time const&amp;)“(?? YProject2 @@ YAAAVTime @ 0 @ ABV10 @ 0 @ Z)c :\ Users \ Eon-Gwei \ documents \ visual studio 2013 \ Projects \ c ++ III_Project2_GW \ c ++ III_Project2_GW \ Time.obj c ++ III_Project2_GW
答案 0 :(得分:0)
Time& tempTime(unsigned hours, unsigned minutes, unsigned seconds);
声明一个名为tempTime
的函数,并return tempTime(lhsHours + rhsHours, lhsMinutes + rhsMinutes, lhsSeconds + rhsSeconds);
调用该函数。由于该函数在任何地方都没有实现,因此会出现链接器错误。
由于
编辑:任何理智的operator +=
可能会返回对其调用对象的引用,因此您应该通过this
修改对象的成员变量,而不是创建新的Time
{1}},并返回*this
。operator +=
实现都会修改左侧操作数,而不是创建新对象。我建议你重新考虑一下你的运营商应该如何运作。