提问人:Renu 提问时间:6/6/2023 最后编辑:Renu 更新时间:6/6/2023 访问量:50
模板化矩阵类的赋值运算符重载
Assignment operator overloading for templated matrix class
问:
我正在为模板矩阵类实现赋值运算符函数。 它应该处理不同的数据类型矩阵分配。例如,整数矩阵被分配给双元矩阵。 为此,我有以下声明:
template<class U> MyMatrix<T>& operator= (const MyMatrix<U> &rhs) {...}
我的问题是,如果我在类声明中实现功能,它就会起作用。但是如果我在类声明之外实现它,比如,
template<class T, class U> MyMatrix<T>& MyMatrix<T>::operator= (const MyMatrix<U> &rhs){...}
我收到以下错误:
error: no declaration matches ‘MyMatrix<T>& MyMatrix<T>::operator=(const MyMatrix<U>&)’
我做错了什么?
答:
1赞
user21908670
6/6/2023
#1
在提供成员模板的类外定义时,必须提供与类模板和成员模板相对应的模板参数子句,如下所示:
template<class T> // parameter clause for class template
template<class U> // parameter clause for member template
MyMatrix<T>& MyMatrix<T>::operator= (const MyMatrix<U> &rhs)
{ // code here
}
评论
template<class T> template<class U> MyMatrix<T>& //etc.