自定义矩阵模板类如何重载乘法?
自定义了一个矩阵模板类,做数乘运算时如果数在前对象在后就要用友元重载一次乘法,但是怎么写都不对。最好的情况是代码能通过编译但是无法调用,一调用链接器就报无法解析的外部命令。最差的情况就是一堆错误,编译都不给通过。
//这是提前声明
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等关键字?
//这是提前声明
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等关键字?
...全文
相关推荐
C++ Matrix类
自己写的C++矩阵类 定义了一些矩阵的操作,包括秩运算,高斯消元法解方程等。
c++模版类 函数重载 矩阵加减乘除等运算
c++模版类 函数重载 矩阵加减乘除等运算
类运算符重载设计定义一个二维方阵类 matrix。通过重载二元运算符“+”、“-”、“*”和一元运算符“~”, 来实现矩阵加、矩阵减、矩阵乘以及矩阵转置。
定义一个二维方阵类 matrix。通过重载二元运算符“+”、“-”、“*”和一元运算符“~”, 来实现矩阵加、矩阵减、矩阵乘以及矩阵转置。
使用C++实现矩阵运算(运算符重载)
这个是使用C++是实现的矩阵基本运算,使用了运算符重载技术和动态生成数组技术!
c++本科作业 矩阵运算 运算符重载
For this task, put your code in the following files: Matrix.cpp, Matrix.h. You are to write a class Matrix which includes appropriate fields associated with 2*2 matrices. A 2*2 matrix takes the following form: (where a, b, c and d are real numbers)


