У вас возникли проблемы с вашим кодом, @BoPersson и @Perter указали на некоторые из них.
Но даже если вы измените то, что они предложили (Here is a live demo on ideone), и я тоже запустил его на VS VS 2015. Компиляторы все еще безумны.
Ideone говорит:
prog.cpp:10:55: warning: friend declaration 'std::ostream& operator&)' declares a non-template function [-Wnon-template-friend]
friend ostream &operator &);
^
prog.cpp:10:55: note: (if this is not what you intended, make sure the function template has already been declared and add after the function name here)
/home/FHMhT9/ccNwcxP0.o: In function `main':
prog.cpp:(.text.startup+0x1b): undefined reference to `operator&)'
collect2: error: ld returned 1 exit status
И VS дает довольно много же ошибки тоже.
Ideone сообщает мне, что объявление друга в классе объявляет функцию без шаблона.
Таким образом, изменить объявление в классе:
friend ostream &operator<< <T> (ostream &, Array<T> &);
// ^^^^^
// I added this <T> to tell the compiler that it is a template function.
Но вам нужно определить функцию перед этим, разрезанная реализацию operator<<
, а затем вставьте его перед классом. Но для этого вам понадобится передовая декларация класса. Итак, наконец, ваш код будет примерно таким:
И я изменил Array<T> &
на const Array<T> &
.
#include <iostream>
template <typename T>
class Array;
template <class T>
std::ostream &operator<< (std::ostream &output, const Array<T> &theArray)
{
output << "abc";
return (output);
}
template <class T> class Array
{
T *pType;
int itsSize;
public:
// template <class T>
friend std::ostream &operator<< <T> (std::ostream &, const Array<T> &);
};
int main()
{
Array<int> theArray;
std::cout << theArray << std::endl;
return 0;
}
и this version now works.
, который не зависит от шаблона. Вы объявляете функцию, но для нее нет определения. – user463035818
Также подпись должна быть 'ostream & operator << (ostream &, const Array &);' –