繁体   English   中英

C ++ LNK2019无法解析的外部符号

[英]C++ LNK2019 unresolved external symbol

我已经阅读了很多有关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对象并使用重载的运算符,似乎没有问题(提供了这些代码,所以它们本身也很好)。

我试图删除所有“时间”符号后面的“&”,但遇到了同样的错误。

这是错误消息:

错误1错误LNK2019:未解决的外部符号“类Project2 :: Time和__cdecl tempTime(unsigned int,unsigned int,unsigned int)”(?tempTime @@ YAAAVTime @ Project2 @@ III @ Z)在函数“类Project2中引用:: Time&__cdecl Project2 :: operator + =(类Project2 :: Time const&,类Project2 :: Time const&)“(?? 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

Time& tempTime(unsigned hours, unsigned minutes, unsigned seconds); 声明一个名为tempTime的函数并return tempTime(lhsHours + rhsHours, lhsMinutes + rhsMinutes, lhsSeconds + rhsSeconds); 调用该函数。 由于该函数在任何地方都没有实现,因此会出现链接器错误。

由于应该假定 operator +=返回对其调用对象的引用,因此您应该通过 this修改对象的成员变量,而不是创建新的 Time ,并返回 *this 编辑: operator +=任何明智的实现都将修改左侧操作数,而不是创建新对象。 我建议您重新考虑操作员的工作方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM