我正在为学校作业编写一个小型日历库的最后阶段,我遇到了一个意想不到且非常令人困惑的问题;当我引入模板时,我的赋值运算符不会被覆盖!
所以结构如下:我有一个抽象类Date
,其中大部分是纯虚函数(包括赋值运算符),然后我有两个子类Gregorian
并Julian
实现了它的所有功能。最后,我为 class 编写了一个模板Calendar
,其中包含今天的日期(以 aGregorian
或Julian
对象的形式)和一些与这个特定问题并不真正相关的其他内容。
问题是当试图设置这个成员时,today
我得到一个长链接器错误:
错误 4 error LNK2019: unresolved external symbol "public: virtual class lab2::Date & __thiscall lab2::Date::operator=(class lab2::Date const &)" (??4Date@lab2@@UAEAAV01@ABV01@@ Z) 在函数“public: class lab2::Gregorian & __thiscall lab2::Gregorian::operator=(class lab2::Gregorian const &)”中引用 (??4Gregorian@lab2@@QAEAAV01@ABV01@@Z) C: \Users...\test.obj 日历
它告诉我operator=
告诉我它在类中找不到函数Date
(显然是因为它是纯虚拟的)。为什么不使用任何被覆盖的?Gregorian::operator=
正在尝试打电话Date::operator=
?
这是出错的简化代码:
namespace cal_lib {
template <typename T>
class Calendar {
public:
Calendar() {
today = T(); // this yields the error
}
private:
T today;
};
}
这是Gregorian.cpp的一个片段:
namespace cal_lib {
class Gregorian : public Date {
public:
Gregorian();
virtual Gregorian& operator=(const Date& date);
virtual Date& add_year(int n = 1);
virtual Date& add_month(int n = 1);
};
// here I'm using Date's constructor to get the current date
Gregorian::Gregorian() {}
Gregorian& Gregorian::operator=(const Date& date) {
if (this != &date) {
// these member variables are specified as
// protected in Date
m_year = 1858;
m_month = 11;
m_day = 17;
add_year(date.mod_julian_day()/365);
add_month((date.mod_julian_day() - mod_julian_day())/31);
operator+=(date.mod_julian_day() - mod_julian_day());
}
}
}
Date 的(默认)构造函数只是将 和 的值设置为今天的日期m_year
:m_month
m_day
Date::Date() {
time_t t;
time(&t);
struct tm* now = gmtime(&t);
m_year = now->tm_year + 1900;
m_month = now->tm_mon + 1;
m_day = now->tm_mday;
}
值得注意的是,这非常有效:
Gregorian g;
Julian j;
g = j; // no problems here
Date* gp = new Gregorian();
Date* jp = new Julian();
*gp = *jp; // no problems here either
这是Calendar
类的实例化方式:
using namespace cal_lib;
Calendar<Gregorian> cal;
我在这里犯了一些非常明显的错误吗?