我有一个类,当我试图在visual studio上编译它时,它给了我4个外部符号,在4个操作符重载上没有解析。它在.h和.cpp文件下面列出的4个操作符重载上显示LNK2019错误。看起来链接器没有正确地链接函数,或者发生了其他事情。
.h
template <class T>
class Ecuatie
{
//some private things
public:
//other function definitions
Ecuatie<int> friend operator+(int x, Ecuatie<int> &e);
Ecuatie<int> friend operator+(Ecuatie<int> &e, int x);
Ecuatie<int> friend operator-(int x, Ecuatie<int> &e);
Ecuatie<int> friend operator-(Ecuatie<int> &e, int x);
};.cpp
template <class T>
Ecuatie<int> operator+(Ecuatie<int> &e, int x) {
string aux = "+";
aux += to_string(x);
str += "+" + aux;
v.push_back(aux);
return (*this);
}
template <class T>
Ecuatie<int> operator+(int x, Ecuatie<int> &e) {
string aux = "";
aux += to_string(x);
str = aux + "+" + str;
if (v.size()) {
v[0] = "+" + v[0];
}
v.push_back("0");
for (int i = v.size() - 1; i >= 0; i--) {
v[i + 1] = v[i];
}
v[0] = aux;
return (*this);
}
template <class T>
Ecuatie<int> operator-(Ecuatie<int> &e, int x) {
string aux = "-";
aux += to_string(x);
v.push_back(aux);
str += "-" + aux;
return (*this);
}
template <class T>
Ecuatie<int> operator-(int x, Ecuatie<int> &e) {
string aux = "-";
aux += to_string(x);
str = aux + "-" + str;
if (v.size()) {
v[0] = "-" + v[0];
}
v.push_back("0");
for (int i = v.size() - 1; i >= 0; i--) {
v[i + 1] = v[i];
}
v[0] = aux;
return (*this);
}你知道为什么,更重要的是如何修复这些错误吗?
发布于 2018-04-24 16:20:12
问题是,您将运算符函数声明为非模板函数,但随后将它们定义为模板函数。
从源文件的定义中删除template<class T>,它应该可以工作。
相关问题:Why can templates only be implemented in the header file?
https://stackoverflow.com/questions/49996616
复制相似问题