使用模板类时,似乎无法包含除 main 以外的任何 cpp 文件.cpp

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

本文关键字:cpp main 包含 文件 任何      更新时间:2023-10-16

我决定将必要的代码减少到显示此错误所需的最低限度。我有一个存在于 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 函数如下:

// 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>

在您的标题中。