使用模板类时,似乎不包括除main.cpp之外的任何cpp文件 [英] Can't seem to include any cpp file other than main.cpp when using template class

查看:165
本文介绍了使用模板类时,似乎不包括除main.cpp之外的任何cpp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定将必要的代码削减到显示此错误所需的最低限度。我有一个STL列表包装模板类,它存在于hc_list.h文件中。整个代码如下:

  // hc_list.h文件
#ifndef HC_LIST_H
#define HC_LIST_H

#include< cstdlib>
#include< list>

template< typename T>
class hcList
{
private:
std :: list< T> selfList; //一个单一的内部STL列表来保存值

public:
hcList(void){};
〜hcList(void){};
//错误发生在
下面的行template< typename U> friend std :: ostream& operator<<(std :: ostream& const hcList< U>&
};
#endif // HC_LIST_H

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

  // main.cpp文件
#include< iostream>
#includehc_list.h
int main()
{
std :: cout< 开始测试< std :: endl;
return 0;
}

这段代码,当输入到CodeBlocks项目时,将编译为0错误或警告。但是,我包含另一个cpp文件,并尝试包括列表头,如下所示:

  // anyNamedFile.cpp文件
#includehc_list.h



当我将任何cpp文件包含到项目中时,我收到编译器错误:

 错误:'&'令牌之前的预期初始化程序



我不明白我做错了什么,真的可以使用一些帮助。

解决方案

您的头文件使用 std :: ostream &

      code> #include< iosfwd> 


I decided to cut the necessary code down to the bare minimum needed to display this error. I have an STL list wrapper template class that exists in hc_list.h file. The entire code is below:

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

This code is included in the main.cpp file, where the main function is below:

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

This code, when entered into a CodeBlocks project will compile as is with 0 errors or warnings. However, then I include another cpp file and attempt to include the list header, like the following:

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

When I include any cpp file into the project, I get a compiler error:

error: expected initializer before '&' token

I do not understand what I am doing wrong, and could really use some help.

解决方案

Your header file uses std::ostream, (just before an &) but does not include any header which might declare it.

Try adding

#include <iosfwd>

in your header.

这篇关于使用模板类时,似乎不包括除main.cpp之外的任何cpp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆