模板类运算符重载的不同错误和警告问题
Different error and warning issues of template class operator overloading
当重载模板类的加法运算符时,我遇到了不同的问题。
我终于找到了一个解决方案,下面的代码可以毫无问题地工作。
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
};
然而,在我对上面的代码进行了一些实验之后,我非常困惑
我更改了类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
如果没有在步骤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
我在步骤1和步骤2中都进行了修改,然后在步骤1中得到相同的警告:
warning: friend declaration 'A<T> operator+(const A<T>&, const A<T>&)' declares a non-template function
我对这些修改引起的问题感到困惑。
<>
在operator +
之后有什么作用?(见第一次修改)- 删除加法运算符重载函数的模板声明有什么效果?(见第二次修改)
- 为什么当我只进行第二次修改时,代码不能运行并返回错误,而当我同时进行第一次和第二次更改时,它可以运行并返回警告
提前感谢!
案例1:friend 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>&
参数的朋友减速模板函数。
- 我在 C++ 代码中遇到错误警告:控制到达非空函数 [-Wreturn 类型] 的末尾
- G++ 编译器未为未定义的方法生成错误/警告
- 一个语句中没有多个 cout 的错误/警告
- Clang:覆盖之前在命令行上指定的所有警告和错误警告标志
- 放置新位置的错误警告
- Xcode 8.3.2 中的错误警告:文件的非可移植路径 - 指定的路径与磁盘上的文件名不同
- 编译错误:(警告:控制到达非空函数 [-wreturn 类型] 的末尾)
- snprintf:相同的代码-在不同的g++编译器上有不同的错误/警告
- 有没有办法自定义编译错误/警告消息
- 获取错误:警告C4715::并非所有控制路径都返回值,但不确定原因
- 导致.exe错误警告
- 如何在 SysntasticCheck for vim 中显示所有" g++ -Wall "错误警告?
- 开发基本的C++代码+检查错误/警告
- 如何使g++为int i=i生成错误/警告
- 我得到以下错误:[警告]多字符字符常量
- C++错误:警告:多字符字符常量/a用于用法
- C++ 在开关中隐式跌倒时强制编译时错误/警告
- 打印矩阵时,C ++程序停止,没有错误警告
- Xcode typedef 的 struct 创建错误/警告
- 主函数给出错误警告