2016-10-09 25 views
1
template <typename T> class Queue 
{ 

template<typename T> ostream& operator<< (ostream& print, const Queue <T>& x) 
    { 
     print<<"\nThe elements are as : \n"; 
     if(q.f!=-1) 
     { 
      int fr=q.f,rr=q.r; 
      while(fr<=rr) 
       print<<q.q[fr++]<<" <- "; 
     } 
     print<<endl; 
    } 
    //other stuffs 
}; 

    In main(): 
    Queue<int> q(n); //object creation 
    cout<<q; //calling the overloaded << function 

它是給我以下錯誤:重載<<與模板:爲什麼我會收到以下錯誤?

C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|16|error: declaration of 'class T'| 
C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|3|error: shadows template parm 'class T'| 
C:\Users\user\Desktop\PROGRAMS\queue_using_classes.cpp|16|error: 'std::ostream& Queue<T>::operator<<(std::ostream&, const Queue<T>&)' must take exactly one argument 
+0

'陰影模板parm'類T''什麼還不清楚呢? – tkausl

+0

我不知道那是什麼錯誤。我只是試圖超載<<運營商與模板..... –

+0

你知道什麼「陰影」是什麼意思? –

回答

1

爲了使用:

Queue<int> q(n); 
cout << q; 

功能

ostream& operator<<(ostream& print, const Queue <T>& x) 

需要被定義爲一個非成員功能。有關此特定過載的更多信息,請參閱my answer to another question

對類模板聲明一個friend函數很棘手。這是一個顯示概念的裸骨節目。

// Forward declaration of the class template 
template <typename T> class Queue; 

// Declaration of the function template. 
template<typename T> std::ostream& operator<< (std::ostream& print, const Queue <T>& x); 

// The class template definition. 
template <typename T> class Queue 
{ 

    // The friend declaration. 
    // This declaration makes sure that operator<<<int> is a friend of Queue<int> 
    // but not a friend of Queue<double> 
    friend std::ostream& operator<<<T> (std::ostream& print, const Queue& x); 
}; 

// Implement the function. 
template<typename T> 
std::ostream& operator<< (std::ostream& print, const Queue <T>& x) 
{ 
    print << "Came here.\n"; 
    return print; 
} 

int main() 
{ 
    Queue<int> a; 
    std::cout << a << std::endl; 
} 
相關問題