模板化矩阵类的赋值运算符重载

Assignment operator overloading for templated matrix class

提问人:Renu 提问时间:6/6/2023 最后编辑:Renu 更新时间:6/6/2023 访问量:50

问:

我正在为模板矩阵类实现赋值运算符函数。 它应该处理不同的数据类型矩阵分配。例如,整数矩阵被分配给双元矩阵。 为此,我有以下声明:

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>&)’

我做错了什么?

C++ 模板 矩阵 赋值运算符

评论

6赞 UnholySheep 6/6/2023
类外定义必须如下所示 - 模板中有一个模板,而不是一个采用 2 个模板参数的模板template<class T> template<class U> MyMatrix<T>& //etc.
0赞 Renu 6/6/2023
@UnholySheep,您能否建议一些资源,让我可以了解有关模板的更多信息?谢谢
0赞 UnholySheep 6/6/2023
我能想到的唯一资源是Andrei Alexandrescu的“现代C++设计” - 但这已经是模板上相当高级的文本。否则,我主要是通过阅读和使用更有经验的程序员编写的代码来学习的

答:

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
}