首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运算符重载时未解析的外部符号

运算符重载时未解析的外部符号
EN

Stack Overflow用户
提问于 2018-04-24 16:14:33
回答 1查看 95关注 0票数 1

我有一个类,当我试图在visual studio上编译它时,它给了我4个外部符号,在4个操作符重载上没有解析。它在.h和.cpp文件下面列出的4个操作符重载上显示LNK2019错误。看起来链接器没有正确地链接函数,或者发生了其他事情。

.h

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
}

你知道为什么,更重要的是如何修复这些错误吗?

EN

Stack Overflow用户

发布于 2018-04-24 16:20:12

问题是,您将运算符函数声明为非模板函数,但随后将它们定义为模板函数。

从源文件的定义中删除template<class T>,它应该可以工作。

相关问题:Why can templates only be implemented in the header file?

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49996616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档