簡體   English   中英

使用模板類時,除main.cpp之外似乎不包含任何cpp文件

[英]Can't seem to include any cpp file other than main.cpp when using template class

我決定將必要的代碼減少到顯示此錯誤所需的最低限度。 我在hc_list.h文件中存在一個STL列表包裝器模板類。 整個代碼如下:

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

#include <cstdlib>
#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){} ;
    // The error occurs on the line below
    template <typename U> friend std::ostream& operator<<(std::ostream &, const hcList<U> &) ;
} ;
#endif // HC_LIST_H

該代碼包含在main.cpp文件中,其主要功能如下:

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

將此代碼輸入CodeBlocks項目后,將按0正確顯示錯誤或警告。 但是,然后我包含另一個cpp文件,並嘗試包含列表標頭,如下所示:

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

當我在項目中包含任何cpp文件時,都會出現編譯器錯誤:

error: expected initializer before '&' token

我不明白自己在做什么錯,真的可以使用一些幫助。

您的頭文件使用std::ostream (在&之前),但不包括任何可能聲明它的頭。

嘗試添加

#include <iosfwd>

在您的標題中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM