自定义矩阵模板类如何重载乘法?

_iChthyosaur _iChthyosaur 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
自定义了一个矩阵模板类,做数乘运算时如果数在前对象在后就要用友元重载一次乘法,但是怎么写都不对。最好的情况是代码能通过编译但是无法调用,一调用链接器就报无法解析的外部命令。最差的情况就是一堆错误,编译都不给通过。
//这是提前声明
template <typename T> class MyMatrix;
template <typename T>
MyMatrix<T> operator*(const T k, const MyMatrix<T> & ma);
//类中声明
friend MyMatrix operator*(const T k, const MyMatrix & ma);
//友元函数定义
template <typename T>
MyNamespace::MyMatrix<T> MyNamespace::operator*(const T k, const MyMatrix<T> & ma)
{
MyMatrix<T> result(ma.row, ma.col);
for (int i = 0; i < result.row; i++)
for (int j = 0; j < result.col; j++)
result.matrix[i][j] = k*ma.matrix[i][j];
return result;
}

这样写能编译就是用不了,等于没写。参考《C++ Primer Plus》没找到友元模板函数的参数既有模板类又有模板变量的情况。难道第一个参数k必须给出确定的int,float,double等关键字?
...全文

相关推荐

评论 34
收藏 已收藏
分享
返回顶部
_iChthyosaur
C++ 语言 65,214 成员 250,514 内容