1

I have a class and when i tried to compile it on visual studio it gave me 4 external symbols unresolved on 4 operator overloads. It gives me LNK2019 error on the 4 operator overloads listed below on the .h and .cpp files. Seems like the linker is not linking the functions correctly or something else is happening.

.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);
}

Any ideas why and more important how to fix these errors?

1 Answers1

1

The problem is that you declare the operator functions as non-template functions, but then define them as template functions.

Remove the template<class T> from the definitions in the source file and it should work.

Related question: Why can templates only be implemented in the header file?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621