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.