如何绕过前向声明

时间:2014-04-24 22:04:25

标签: c++ sorting vector forward-declaration

这个程序有效,但是如果没有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;
            }    
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有时需要前方声明。如果您将UListoperator<<置于sort的定义之上,则可以仅使用UList的前向声明。我不确定为什么sort在不同的头文件中。如果您希望按照原样保持代码的有序性,那么前向声明是必要的。

相关问题