1

iosfwdを含めると、標準文字列を含む出力ストリームが機能しなくなる理由を理解しようとしています。

// hc_list.h file
#ifndef HC_LIST_H
#define HC_LIST_H

#include <cstdlib>
#include <iosfwd> // including this file makes the output operator throw errors
#include <list>

template <typename T>
class hcList
{
    private:
    std::list<T> selfList ; // a single internal STL list to hold the values

    public:
    hcList(void) {} ;
    ~hcList(void){} ;
    template <typename U> friend std::ostream& operator<<(std::ostream &, const hcList<U> &) ;
} ;

template <typename U>
std::ostream& operator<<(std::ostream &out, const hcList<U> &outList)
{
    out << "test" << std::endl ; // this line throws two errors, stated below
    return out ;
}
#endif // HC_LIST_H

このコードはmain.cppファイルに含まれており、main関数は次のとおりです。

// main.cpp file
#include <iostream>
#include "hc_list.h"
int main()
{
    std::cout << "Begin Test" << std::endl;
    return 0;
}

このコードを実際に利用してエラーを生成するには、リストヘッダーファイルを含む空のcppファイルが必要です。

// anyNamedFile.cpp file
#include "hc_list.h"

コンパイルしようとすると、次のエラーが発生します。

error: no match for 'operator<<' in 'out<< "test"'
error: 'endl' is not a part of 'std'

std名前空間が台無しになり、文字列を出力できなくなった原因は何ですか?

4

1 に答える 1

3

ここで 2 つの問題があります。最初の問題は、 を使用していることですが、これstd::endlは に定義されており<ostream>、含まれていません。

<iosfwd>2 番目の問題は、多くの iostream 型を前方宣言するheader のみを含めていることです。前方宣言は、型が存在することをコンパイラに知らせます。ただし、これらのタイプの機能を使用しようとしています。あなたはそうしているので<ostream>、ではなく、を含める必要があります<iosfwd><ostream>が含まれstd::endlているため、すべてを処理する必要があります。

于 2012-05-12T17:02:59.880 に答える