2014-04-24 2 views
0

이 프로그램이 작동하지만 UList.H의 전달 선언없이이 프로그램을 작동하게하려면 어떻게해야합니까? 그들을 제거하면 오류가 발생합니다. 이 오류를보고 싶다면 https://stackoverflow.com/questions/23278943/how-to-implement-sort-functions-using-vectors 다른 질문을 확인하십시오.전달 선언을 무시하는 방법

UList.h

#ifndef PROJ_ULIST_H 
#define PROJ_ULIST_H 

#include <iostream> 
#include <vector> 

//forward declarations of UList and friended functions 
template<class T> class UList; 

template<class T> 
std::ostream& operator<<(std::ostream&, const UList<T>&); 

template<class T> 
void sort(UList<T>&); 

template <class T> 
class UList{ 
public: 
    UList(size_t=10); 
    void insert(const T&); 
    bool erase(const T&); 
    bool find(const T&); 
    size_t size() const; 
    bool empty() const; 
    friend void sort<T>(UList<T>&); 
    friend std::ostream& operator << <T>(std::ostream&, const UList<T>&); 

protected: 
    std::vector<T> items; 
}; 


template <class T> 
UList<T>::UList(size_t size){ 
    std::vector<T> items(size); 
} 


template <class T> 
bool UList<T>::find(const T& element){ 
    bool found=false; 
    size_t index=0; 
    while(index<items.size()){ 
     if(items.at(index)==element) 
      found=true; 
     index++; 
    } 
    return found; 
} 


template <class T> 
size_t UList<T>::size() const{ 
    return items.size(); 
} 


template <class T> 
bool UList<T>::empty() const{ 
    return items.empty(); 
} 

template<class T> 
std::ostream& operator << (std::ostream& out, const UList<T>& List){ 
    if(List.items.empty()) 
     out<<"list is empty."<<std::endl; 
    else{ 
     for(size_t index=0;index<List.items.size();index++){ 
      out<<List.items.at(index); 
       if(index<List.items.size()-1) 
        out<<" "; 
     } 
    } 
    return out; 
} 


#endif 

sortBS.h

#ifndef PROJ_SORTBS_H 
#define PROJ_SORTBS_H 
#include <algorithm> 
#include <vector> 
#include "UList.h" 

template <class T> 
void sort(UList<T>& List){ 
    std::vector<T>& items=List.items; 
    size_t len=items.size(); 
    bool swapped = true; 

    while((len--!=0)&& swapped){ 
     swapped=false; 
     for(size_t i=0; i<len;++i){ 
      if(items[i+1]<items[i]){ 
       std::swap(items[i+1], items[i]); 
       swapped=true; 
      }  
     } 
    } 
} 
+0

_What_ 오류가 있습니까? 친구 선언은 충분해야하지만, ADL에 대한 해당 함수의 조회가 제한되어 있으므로 코드에서 문제가 발생할 수 있습니다. 당신은 (IIRC) 나중에 그것을 재확인, _after_'UList', 주위에 얻을 수 있습니다. 나는 구체적인 질문이 없기 때문에 나는 단지 추측 할 수있다. –

답변

0

때때로 앞으로 선언이 필요하다. UList의 정의 위에 operator<<sort을 입력하면 앞으로 선언문을 UList과 함께 만들 수 있습니다. 왜 sort이 다른 헤더 파일에 있는지 확실하지 않습니다. 코드를 그대로 유지하려면 앞으로 선언해야합니다.

+0

sort는 다른 정렬 함수에 대해 여러 헤더 파일을 작성하기 때문에 differnt 헤더 파일에 있습니다. 나는 무례하다고 생각하지 않지만 교수는 그렇지 않다고 생각합니다. 그는 그들이 꼭 필요한 것은 아니며 그것을 고치라고 말했다. 그러나 어떻게 말해주지 않을 것이다. – user3555573

+0

전혀 무례하지 않습니다. 이 경우에는 그가 맞을 수도 있습니다. (비록 그가 필요 없다고 제안했다해도 나는 그것이 사실이라고 믿지 않는다.) 바라건대 다른 누군가 (또는 당신!)가 해결책을 제시하고 그것을 게시하기를 바랍니다. :) – ooga

+0

내 교수는 앞으로 선언문이 없으며'sort '와'operator <<'에 대한 그의 선언문은 모두'UList' 클래스 안에 있습니다 – user3555573

관련 문제