为模板矩阵类重载赋值运算符。

huangapple go评论60阅读模式
英文:

Assignment operator overloading for templated matrix class

问题

I am implementing assignment operator function for a template matrix class.
It should take care of different datatype matrix assignments. eg Integer matrix is assigned to a double matrix.
for that i have following declaration:

template MyMatrix& operator= (const MyMatrix &rhs) {...}

My problem is, if i implement the function within class declaration, it works. But if i implement it outside the class declaration like,

template<class T, class U> MyMatrix& MyMatrix::operator= (const MyMatrix &rhs){...}

i get following error:

error: no declaration matches 'MyMatrix& MyMatrix::operator=(const MyMatrix&)'

What am i doing wrong?

英文:

I am implementing assignment operator function for a template matrix class.
It should take care of different datatype matrix assignments. eg Integer matrix is assigned to a double matrix.
for that i have following declaration:

template&lt;class U&gt; MyMatrix&lt;T&gt;&amp; operator= (const MyMatrix&lt;U&gt; &amp;rhs) {...}

My problem is, if i implement the fuction within class declaration, it works. But if i implement it outside the class declaration like,

template&lt;class T, class U&gt; MyMatrix&lt;T&gt;&amp; MyMatrix&lt;T&gt;::operator= (const MyMatrix&lt;U&gt; &amp;rhs){...}

i get following error:

error: no declaration matches ‘MyMatrix&lt;T&gt;&amp; MyMatrix&lt;T&gt;::operator=(const MyMatrix&lt;U&gt;&amp;)’

What am i doing wrong?

答案1

得分: 1

当提供类成员模板的课外定义时,您必须提供与类模板以及成员模板对应的模板参数子句,如下所示:

template<class T> // 类模板的参数子句
template<class U> // 成员模板的参数子句
MyMatrix<T>& MyMatrix<T>::operator= (const MyMatrix<U>& rhs)
{  // 在此处添加代码
}
英文:

When providing out of class definition of a member template you've to provide the template parameter clause correspondimg to both the class template as well as the member template as shown below:

template&lt;class T&gt; // parameter clause for class template 
template&lt;class U&gt; // parameter clause for member template
MyMatrix&lt;T&gt;&amp; MyMatrix&lt;T&gt;::operator= (const MyMatrix&lt;U&gt; &amp;rhs)
{  // code here
}

huangapple
  • 本文由 发表于 2023年6月6日 17:14:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76413111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定