首页 文章

C LNK2019未解析的外部符号

提问于
浏览
2

我已阅读很多关于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对象并使用了重载的运算符,似乎没有问题(这些代码都是提供的,因此它们本身就很好) .

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

And here is the error message:

错误1个错误LNK2019:解析外部符号 “类Project2的::时间和__cdecl tempTime(无符号整数,无符号整型,无符号整型)” 函数“类Project2的引用(tempTime @@ @ YAAAVTime Project2的@@ III @ Z): :时间&__cdecl Project2的::运算=(类Project2的::时间常量&,类Project2的::时间常量&)”(?? YProject2 @@ @ YAAAVTime 0 @ ABV10 @ 0 @ Z)C:\用户\ Eon- Gwei \ documents \ visual studio 2013 \ Projects \ c III_Project2_GW \ c III_Project2_GW \ Time.obj c III_Project2_GW

1 回答

  • 0

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

    因为operator =可能应该返回对它被调用的对象的引用,所以你应该通过它来修改对象的成员变量,而不是创建一个新的Time,并返回* this . 编辑:任何理智的 operator += 实现都会修改左侧操作数,而不是创建新对象 . 我建议你重新考虑一下你的运营商应该如何运作 .

相关问题