重载 C++ 中的乘法运算符
Overloading the multiplication operator in c++
我已经为 LAPACK 编写了一个C++接口,但我遇到了一些内存问题,这些问题让我重新考虑了一些运算符重载。
现在,我已经在类定义之外重载了运算符*(但作为矩阵类的朋友(,它接受两个矩阵对象,为第三个对象分配适当的维度,使用 D(GE/SY(MM 计算乘积(存储到新分配矩阵的内部存储中(,然后返回指向该新矩阵的指针。即
class Matrix {
...
friend Matrix* operator*(const Matrix&, const Matrix&);
...
}
Matrix* operator*(const Matrix& m1, const Matrix& m2) {
Matrix *prod = new Matrix(m1.rows_, m2.cols_);
if(m1.cols_!=m2.rows_) {
throw 3008;
} else {
double alpha = 1.0;
double beta = 0.0;
if(m1.symm_=='G' && m2.symm_=='G'){
dgemm_(&m1.trans_,&m2.trans_,&m1.rows_,&m2.cols_,&m1.cols_,&alpha,m1.data_,
&m1.rows_,m2.data_,&m1.cols_,&beta,prod->data_,&m2.cols_);
} else if(m1.symm_=='S'){
char SIDE = 'L';
char UPLO = 'L';
dsymm_(&SIDE,&UPLO,&m1.rows_,&m2.cols_,&alpha,m1.data_,&m1.rows_,m2.data_,
&m2.cols_,&beta,prod->data_,&m2.cols_);
} else if(m2.symm_=='S'){
char SIDE = 'R';
char UPLO = 'L';
dsymm_(&SIDE,&UPLO,&m2.rows_,&m1.cols_,&alpha,m2.data_,&m2.rows_,m1.data_,
&m1.cols_,&beta,prod->data_,&m1.cols_);
};
}
return prod;
};
然后我利用
Matrix *A, *B, *C;
// def of A and B
C = (*A)*(*B);
这工作得很好。我遇到的问题是每次执行此操作时都必须分配一个新矩阵。我希望能够做的是分配一次C
矩阵,然后将A
和B
的乘积放入C
的内部存储中(C->data_
(。从我能够在运算符重载上找到的内容来看,我找不到一种很好的方法来做到这一点。我知道我可以使用成员函数来执行此操作,(即 C->mult(A,B)
(,但如果可能的话,我想避免这种情况(我正在编写代码是为了便于非 CSE 类型的开发(。任何想法将不胜感激。
class Matrix
{
struct Product
{
const Matrix* a;
const Matrix* b;
};
Matrix& operator = (const Product& p)
{
// if this matrix dims differ from required by product of p.a and p.b
// reallocate it first and set dims
// {
// rows = ....; cols = ....;
// delete [] data;
// data = new [rows*cols];
// }
// then calculate product
// data[0] = ...;
// ...
return *this;
}
Product operator * (const Matrix& op) const
{
Product p;
p.a = this;
p.b = &op;
return p;
}
int rows,cols;
double* data;
/// your Matrix stuff
// ...
};
void test()
{
Matrix a(4,2),b(2,4),c;
c = a * b; // (note a*b returns Product without calculating its result
// result is calculated inside = operator
c = a * b; // note that this time c is initialized to correct size so no
// additional reallocations will occur
}
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<