【问题标题】:Error 'declares a non-template function' in C++ [closed]C ++中的错误“声明非模板函数”[关闭]
【发布时间】:2015-12-28 16:05:02
【问题描述】:

我用 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.cc 行~112 是什么样的?
  • 它包含这个:int Array::compare(Array* ar2)
  • friend 问题只是一个警告,但第 112 行还有一个错误,您未能提供完整代码。我投票赞成关闭。
  • 我认为问题已经定义好了,我没有添加所有代码,我添加了错误和产生错误的 ligns,这也是由于 c++ 版本的问题,所以我不明白你为什么阻止我的帖子,为什么你认为我不尊重网站图表,问题是最小的,完整的......所以我认为你必须支持我的帖子并回馈我的观点:(

标签: c++ ubuntu makefile


【解决方案1】:

如果你的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&lt;Items&gt;&amp; 所写,声明了对Array 类的Items 特化的引用,但您的类不是模板,因此您不能传递模板参数。

如果你的Array应该是一个模板,你应该这样声明它

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

【讨论】:

  • 我的印象是这个类确实是模板化的,但是模板部分只是没有包含在 OP 中(因此需要一个 MCVE)。
  • 我猜Array毕竟是一个模板,但OP未能提供所需的信息。
  • 可以(因此应该)不要在Array&lt;Items&gt; 的定义中省略&lt;Items&gt;,因为Array 自动引用Array&lt;Items&gt;
  • @Walter 哎呀,你是对的!已编辑以解决该问题。
  • @CoeyKramer : 我不能'消除 Array 因为在 Array.cc 中所有的实现都是基于 例如'template void Array:: Realloc (int newlen) { totSz = Util::Realloc (newlen, sizeof(Items), theAry); }
猜你喜欢
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多