I am using Microsoft Visual Studio for source code editor, and when I try to compile the below code I got an linker error:
LNK2019 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class X<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$X@H@@@Z) referenced in function _main Zadatak7.19.04.2021 C:\Users\AT95\Desktop\Zadatak7.19.04.2021\Zadatak7.19.04.2021\main.obj 1
What must I do to make this program work correctly?
I want you to look at the definition of the overloading operator<<
because
that method is causing errors.
#include <iostream>
template <class T>
class X
{
private:
int index, capacity;
T* collection{};
public:
X(const int nmb, const T* array)
{
index = 0;
capacity = nmb;
collection = new(T[nmb]);
for (int i = 0; i < nmb; i++)
collection[index++] = array[i];
}
X(const X& other)
{
index = other.index;
capacity = other.capacity;
collection = new(T[other.capacity]);
if(other.index < other.capacity)
for (int i = 0; i < other.index; i++)
collection[i] = other.collection[i];
}
~X() { delete[] collection; }
friend std::ostream& operator<<(std::ostream&, X<T>&);
};
template <class T>
std::ostream& operator<<(std::ostream& out, X<T>& other)
{
for (int i = 0; i < other.index; i++)
out << i + 1 << ". " << other.collection[i];
return out;
}
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, n = sizeof(array)/sizeof(int);
X<int> x(n, array), b(x);
std::cout << x;
return 0;
}