Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Для новичков > Перегрузка operator<< и шаблоны


Автор: S3_ 23.9.2009, 22:39
Есть небольшая программа, реализующая односвязный список, вот вкратце код:

Код

#include <iostream>
#include <conio.h>

using namespace std;

template <class T>           // один элемент списка
struct term
{
    term(): data(NULL), next(NULL) {}
    term(T d, term<T>* n = NULL): data(d), next(n) {}
    void print() { cout<<data<<"\t"; }
    term<T>* next;
    T data;
};

template <class T>
class list              //наш класс
{
public:
    list(): h(NULL) {}             //по умолчанию
    list(list<T>& ls);               //копирующий
    list(T a[], int n);
    void add (term<T>* t);
    void print();
    list<T>& operator=(list<T>& ls);
    T operator[] (int i);
    friend ostream& operator<< (ostream& out, list<T> ls);        //вывод
private:
    void reverse();
    void clear();
    term<T>* h;
};
 // тут реализация всех конструкторов, деструкторов и тд. и тп.

template <class T>
ostream& operator<< (ostream& out, list<T> ls)       //неправильно почемуто (((
{
/*   
       term<T>* temp;
    temp = ls.h;
    while (temp)
    {
        out<<temp->data;
        temp = temp->next;
    }
*/
    return *this;
}

void main()
{
    double a[5] = {1.7,2.3,3.4,4.5,5.7};
    double b[7] = {7.0,6.4,5.5,4.6,3.7,2.8,1.3};
    list<double> A(a, 5);
    
    cout<<A;             //вот сдесь ошипка
    getch();
}


Ошибка такого содержания:

Цитата

TemplateList 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 list<double>)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@V?$list@N@@@Z) referenced in function _main


Как перегрузить вывод с шаблонами???
Заранее спасибо smile

Автор: GoldFinch 23.9.2009, 22:42
Код

template <class T>
ostream& operator<< (ostream& out, list<T> ls)       //неправильно почемуто (((
{
    return *this;
}

вот тут должна быть ошибка компиляции, потому что this тут неуместен

Автор: bsa 23.9.2009, 23:19
Код
template <class T>
ostream& operator<<(ostream& out, const list<T> &ls)       //неправильно почемуто (((
{
/*       term<T>* temp;
    temp = ls.h;
    while (temp)
    {
        out<<temp->data;
        temp = temp->next;
    }
*/
    return out;


Код
    list(list<T>& ls);               //копирующий
Это не копирующий. Он записывается так:
Код
    list(const list<T>& ls);               //копирующий

Автор: zim22 24.9.2009, 07:54
Цитата(bsa @  23.9.2009,  23:19 Найти цитируемый пост)
Это не копирующий. Он записывается так:

копирующий.  const писать не обязательно.
Цитата

Standard 2003/12.1
10. A copy constructor for a class X is a constructor with a first parameter of type X& or of type const  X&.
[Note: see 12.8 for more information on copy constructors.  ]


Автор: S3_ 24.9.2009, 16:34
Код

return out; 

тоже ставил, все равно таже ошибка (((

Автор: zim22 24.9.2009, 17:17
friend ostream& operator<< <T>(ostream& out, list<T> ls);        //вывод

Автор: S3_ 24.9.2009, 21:03
Цитата(zim22 @  24.9.2009,  17:17 Найти цитируемый пост)
friend ostream& operator<< <T>(ostream& out, list<T> ls);        //вывод 


Ааааа... Спасибо, работает smile)) Только чтото он выводит лажу ))) Ладно, это уже другая проблема )))

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)