错误"声明非模板函数"C++

Error 'declares a non-template function' in C++

本文关键字:函数 C++ 声明 错误      更新时间:2023-10-16

我用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年开发的。

如果您的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>&声明了对Array类的Items专用化的引用,但您的类不是模板,因此无法传递模板参数。

如果您的Array应该是一个模板,那么您应该将其声明为这样的

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