错误'在C ++中声明一个非模板函数'

时间:2015-12-28 16:05:02

标签: c++ ubuntu makefile

我用make命令编译一个项目,但这给了我这些错误:

g++ -std=gnu++11 -c Array.cc       
In file included from Array.cc:5:0:
Array.h:9:65: warning: friend declaration ‘std::ostream&    operator<<(std::ostream&, Array<Items>&)’ declares a non-template function [-Wnon-template-friend]
friend ostream& operator << (ostream& fout, Array<Items>& ary);
                                                             ^
Array.h:9:65: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) 
In file included from Array.cc:9:0:
List.h:28:64: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, List<Items>&)’ declares a non-template function [-Wnon-template-friend]
friend ostream& operator << (ostream& fout, List<Items>& lst);   
                                                            ^
 Array.cc:112:5: error: specializing member ‘Array<int>::compare’ requires ‘template<>’ syntax
int Array<int>::compare(Array<int>* ar2)
 ^
Makefile:30: recipe for target 'Array.o' failed
make: *** [Array.o] Error 1 

Array.cc中的代码是

#include "Array.h"

Array.h:9:65中的代码是:

class Array{
    friend ostream& operator << (ostream& fout, Array<Items>& ary);
  private:
  int theSz;
  int totSz;
  Items *theAry;

你能解释一下这些错误吗?我使用Ubuntu 15.10。也许这些来自C ++中已弃用的函数,因为该算法是在2005年开发的。

1 个答案:

答案 0 :(得分:2)

如果您的Array不是模板,您的函数应该有签名

friend ostream& operator << (ostream& fout, Array& ary);

然后,您可以在该功能中循环ary.theAry。像

这样的东西
ostream& operator << (ostream& fout, Array& ary)
{
    for (int i = 0; i < ary.theSz; ++i)
    {
        fout << ary.theAry[i] << " ";
    }
}

正如书面Array<Items>&声明对Items类的Array专门化的引用,但您的类不是模板,因此您无法传递模板参数。

如果您的Array班级应该是模板,则应将其声明为

template <class Items>
class Array
{
  friend ostream& operator << (ostream& fout, Array& ary);
  private:
  int theSz;
  int totSz;
  Items *theAry;
};
相关问题