模板类运算符重载的不同错误和警告问题

Different error and warning issues of template class operator overloading

本文关键字:错误 警告 问题 运算符 重载      更新时间:2023-10-16

当重载模板类的加法运算符时,我遇到了不同的问题。

我终于找到了一个解决方案,下面的代码可以毫无问题地工作。

template<class T>
class A;
template<class T>
A<T> operator + (const A<T>& , const A<T>&);
template <class T>
A<T> operator+ (A<T> & a1, A<T> & a2){
//the definition of the function
}
template <class T>
class A{
friend A<T> operator +<> (const A<T>& , const A<T>& );
private: //...whatever
public: //...whatever
};

然而,在我对上面的代码进行了一些实验之后,我非常困惑

  1. 我更改了类A中的友元函数声明
    friend A<T> operator +<> (const A<T>& , const A<T>& );
    friend A<T> operator + (const A<T>& , const A<T>& );
    (删除operator +后的<>)
    然后代码可以运行并给出结果,但我得到警告warning: friend declaration 'A<T> operator+(const A<T>&, const A<T>&)' declares a non-template function

  2. 如果没有在步骤1中进行修改,我将删除加法运算符重载函数的模板声明。所以下面的代码被删除了:

    template<class T> A<T> operator + (const A<T>& , const A<T>&);

    然后我得到一个错误:error: template-id 'operator+<>' for 'A<int> operator+(const A<int>&, const A<int>&)' does not match any template declaration

  3. 我在步骤1和步骤2中都进行了修改,然后在步骤1中得到相同的警告:warning: friend declaration 'A<T> operator+(const A<T>&, const A<T>&)' declares a non-template function


我对这些修改引起的问题感到困惑。

  1. <>operator +之后有什么作用?(见第一次修改)
  2. 删除加法运算符重载函数的模板声明有什么效果?(见第二次修改)
  3. 为什么当我只进行第二次修改时,代码不能运行并返回错误,而当我同时进行第一次和第二次更改时,它可以运行并返回警告

提前感谢!

案例1friend A<T> operator +<> (const A<T>& , const A<T>& )实际上是以下函数对类型T(这是类模板的类型)的友好专门化。

template<class T>
A<T> operator + (const A<T>& , const A<T>&);

如果你想把这个函数专门用于int这样的特定类型,你可以这样做:

template<>
A<int> operator+(const A<int>&, const A<int>&)
{
}

所以你的朋友函数是一个专门的朋友函数。

当你删除<>时,你的朋友函数变成了一个普通的朋友函数,但你实际的operator+是一个模板函数。编译器警告您,因为您的类定义有友元函数的非模板声明(没有模板),但友元函数定义是一个函数模板。将好友功能更改为以下功能可取消警告。

template<class T1>
friend A<T1> operator+ (const A<T1>&, const A<T1>&);

情况2:您会得到该错误,因为您的减速度和operator +的定义在参数的const限定符中不同。实际上,它们是两个完全不同的函数,第二个函数并不是第一个函数的定义。将const添加到函数定义的参数中。

事实上,当你删除这个代码:

template<class T>
A<T> operator + (const A<T>& , const A<T>&);

编译器找不到一个使用两个const A<T>&参数的朋友减速模板函数。