проблемы Ostream - PullRequest
       5

проблемы Ostream

2 голосов
/ 28 марта 2012

Итак, у меня есть два класса внутри одного файла;ArrayLinkedList и ArrayLinkedListRow Внутри первого упомянутого у меня есть метод

template<class T> friend ostream& operator <<(ostream& s, ArrayLinkedList<T>& ll){
    //Extra code for giving s content
    return s;   
}

, а также наличие

template<class T> friend ostream& operator <<(ostream& s, ArrayLinkedListRow<T>& ll){
        //Extra code for giving s content
        return s;   
    }

внутри ArrayLinkedListRow.

Я получаюследующая ошибка

Ошибка 1 ошибка C2995: 'std :: ostream & operator << (std :: ostream &, ArrayLinkedList &)': шаблон функции уже определен </p>

и это сводит меня с ума, не зная, как это исправить.Я провел свое исследование, но все еще не могу понять, что делать.Я твердо верю, что эти два класса могут быть связаны в этой проблеме, несмотря на ошибку, указывающую только на одну строку.

Дополнительная информация: Это заголовок класса ArrayLinkedList для тех, кто смущен моим кратким объяснением.

template<class DT>
class ArrayLinkedList {

private:
    DT* _info[MAX_SIZE];  // store data
    int _next[MAX_SIZE];   // next node
    int _nextEmpty[MAX_SIZE];  //next empty slot

    ArrayClass< ArrayLinkedListRow<DT> >* _rows;
    int _head;   // head of the list
    int _firstEmpty;   // first empty slot
    int _size;
    void copy(const ArrayLinkedList<DT>& ll);//copy from another list
    // add a new node with next as it's next node and returns the index of new node
    int newNode( DT& newObject, int next);

public:
    ArrayLinkedList();    // empty and copy constructors
    ArrayLinkedList(const ArrayLinkedList<DT>& ll); 
    //copy constructors linked list object to an existing object. This is a deep copy.
    ~ArrayLinkedList();   // destructor

    ArrayLinkedList(DT& newObject);   // Constructor that create a list with newObject as the head
    ArrayLinkedList(int capacity); // Constructor with a give capacity
    ArrayLinkedList(DT& newObject,int capacity);// Constructor with newObject as the head and capacity

    bool isEmpty();    // is the list empty?
    int size();  // return the number of nodes stored

    void add(DT& newObject); // add an object to the tail
    void insertAt(DT& newObject, int position); // insert an object at the position specified

    DT remove(); // remove the head
    DT removeAt(int position);  // remove an object at the position specified

    int find(DT key); // find the object that matches key, index of the object

    void operator=(const ArrayLinkedList<DT>& ll);  // = operator
    // overloading [] operator, return a reference to object at the
    // Add a new data element to the start of a linked list.

    DT& operator[] (const int position);     // position in the linked list

    // ostream operator
    template<class T> friend ostream& operator <<(ostream& s, ArrayLinkedList<T>& ll){
        return s;   
    }

    void displayRaw(); // display raw data of the data members
};

1 Ответ

1 голос
/ 28 марта 2012

Попробуйте удалить template<class T> часть:

friend ostream& operator <<(ostream& s, ArrayLinkedList& ll){
   //Extra code for giving s content
   return s;   
}
// and analogically with  ArrayLinkedListRow

Причина, по которой это работает, указана здесь :

  • Если вы объявляете переменнуюArrayLinkedList<int>, тогда и только тогда operator << создается с шаблоном-параметром T и DT (который не используется).Если вы скомпилируете это, все будет работать нормально.
  • Если вы добавите переменную типа ArrayLinkedList<float>, оператор будет определен во второй раз, и это создаст ошибку.

Работатолько с DT заставляет его работать как положено.

...