-1

I am trying to overload the += operator in my class, however, I keep getting linker errors. The errors are as following: LNK2019 unresolved external symbol "void __cdecl operator+=(class MyClass<int> &,int)" (??Y@YAXAAV?$MyClass@H@@H@Z) referenced in function _main Project2. Though, everything other than the += operator overload part works just as expected.

Here's my code:

#include <iostream>

template <class T>
class MyClass
{
public:
    MyClass();
    void setVal(T x);
    T getVal();

    friend void operator +=(MyClass &my_obj, T val);

private:
    T val;
};

template <class T>
MyClass<T>::MyClass()
{}

template <class T>
void MyClass<T>::setVal(T x)
{
    val = x;
}

template <class T>
T MyClass<T>::getVal()
{
    return val;
}

//The trouble:
template <class T>
void operator +=(MyClass<T> &my_obj, T x)
{
    T new_val = my_obj.val;
    new_val += x;
    my_obj.setVal(new_val);
}

int main()
{
    MyClass<int> var = MyClass<int>();
    var.setVal(5);
    var += 1;

    std::cout << var.getVal() << std::endl;

    system("pause");
    return 0;
}

I've tried looking up similar questions but did not find anything the helped me solve this issue.

Ayaan Siddiqui
  • 300
  • 1
  • 3
  • 10
  • Close to duplicate of [C++ : friend declaration ‘declares a non-template function](https://stackoverflow.com/questions/10787655/c-friend-declaration-declares-a-non-template-function) – PaulMcKenzie Jun 26 '18 at 01:01
  • This is ill-formed, and your compiler is broken. Find a better C++ compiler, that accurately informs you that you cannot declare a friend template function this way. – Sam Varshavchik Jun 26 '18 at 01:23

1 Answers1

0

Why not just define the function inside the class? That way, you could just use

MyClass<T>& operator +=(const T& rhs)
{
    val += rhs;
    return *this;
}

Note the use of += inside the implementation of operator+=. This works because the += is already implemented because it's the += for built in types. Normally, you should use val = val + rhs because you're implementing the += so it doesn't make sense to use it inside the implementation.

If you want to define it outside of class, it's going to be a bit more troublesome.

In your class, you need to declare

template<typename U>
friend MyClass<U>& operator +=(MyClass<U>& lhs, const U& rhs);

Then for function definition outside class

template<typename U>
MyClass<U>& operator +=(MyClass<U>& lhs, const U& rhs)
{
  lhs.val += rhs;
  return lhs;
}
Nyque
  • 351
  • 3
  • 10