C++ 运算符重载时未解析的外部符号
我有一个类,当我试图在VisualStudio上编译它时,它给了我4个外部符号,在4个运算符重载上无法解析。它在下面列出的.h和.cpp文件中的4个运算符重载上给出了LNK2019错误。链接器似乎没有正确链接函数,或者发生了其他情况 hC++ 运算符重载时未解析的外部符号,c++,visual-studio,oop,C++,Visual Studio,Oop,我有一个类,当我试图在VisualStudio上编译它时,它给了我4个外部符号,在4个运算符重载上无法解析。它在下面列出的.h和.cpp文件中的4个运算符重载上给出了LNK2019错误。链接器似乎没有正确链接函数,或者发生了其他情况 h 模板 Ecuatie类 { //一些私事 公众: //其他函数定义 Ecuatie friend operator+(整数x,Ecuatie&e); Ecuatie友元运算符+(Ecuatie&e,int x); Ecuatie友元运算符-(int x,Ecua
模板
Ecuatie类
{
//一些私事
公众:
//其他函数定义
Ecuatie friend operator+(整数x,Ecuatie&e);
Ecuatie友元运算符+(Ecuatie&e,int x);
Ecuatie友元运算符-(int x,Ecuatie&e);
Ecuatie友元运算符-(Ecuatie&e,int x);
};
.cpp
模板
Ecuatie运算符+(Ecuatie&e,int x){
字符串aux=“+”;
aux+=至_字符串(x);
str+=“+”+aux;
v、 推回(辅助);
返回(*本条);
}
模板
Ecuatie操作员+(int x,Ecuatie&e){
字符串aux=“”;
aux+=至_字符串(x);
str=aux++“++”str;
如果(v.size()){
v[0]=“+”+v[0];
}
v、 推回(“0”);
对于(int i=v.size()-1;i>=0;i--){
v[i+1]=v[i];
}
v[0]=aux;
返回(*本条);
}
模板
Ecuatie运算符-(Ecuatie&e,int x){
字符串aux=“-”;
aux+=至_字符串(x);
v、 推回(辅助);
str+=“-”+aux;
返回(*本条);
}
模板
Ecuatie运算符-(int x,Ecuatie&e){
字符串aux=“-”;
aux+=至_字符串(x);
str=aux+“-”+str;
如果(v.size()){
v[0]=“-”+v[0];
}
v、 推回(“0”);
对于(int i=v.size()-1;i>=0;i--){
v[i+1]=v[i];
}
v[0]=aux;
返回(*本条);
}
您知道为什么以及更重要的是如何修复这些错误吗?问题在于您将运算符函数声明为非模板函数,然后将它们定义为模板函数 从源文件中的定义中删除
模板
,它应该可以工作
相关问题:您是否打算让这些操作员仅适用于
Ecuatie
?
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);
};
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);
}