C++中的效率和赋值运算符重载
Efficent Sum and Assignment operator overloading in C++
嗨,我正在用 c++
实现一个矩阵类我知道有一些很棒的库可以像opencv一样做到这一点,但我需要自己做。
例如,如果我实现总和,我可以像这样做
class Mat{
public:
double* data;
int rows,cols;
Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}
};
void Sum(Mat& A,Mat& B,Mat& C){
for (int i = 0; i < A.rows*A.cols; ++i){
C.data[i] = A.data[i]+B.data[i];
}
}
int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);
//do the sum
sum(A,B,C);
}
我想得到这样更具可读性的东西,但又不损失效率
C = A + B
这样 C 每次都会重新分配,我不希望这样
谢谢你的时间
延迟计算。
class MatAccess {
friend class Mat;
friend class MatOpAdd;
virtual double operator[](int index) const = 0;
};
class MatOpAdd: public MatAccess {
friend class Mat;
private:
const MatAccess& left;
const MatAccess& right;
MatOpAdd(const MatAccess& left, const MatAccess& right):
left(left), right(right) {}
double operator[](int index) const {
return left[index] + right[index];
}
};
class Mat: public MatAccess{
public:
double* data;
int rows,cols;
Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}
MatOpAdd operator +(const MatAccess& other) {
return MatOpAdd(*this, other);
}
const Mat& operator = (const MatAccess& other) {
for(int i = 0; i < rows*cols; ++i) {
data[i] = other[i];
}
return *this;
}
private:
double operator[](int index) const {
return data[index];
}
double& operator[](int index) {
return data[index];
}
};
int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);
//do the sum
C = A + B;
}
现在,"+"计算将在"运算符="中完成
我会改变的事情:
-
MatAccess
应包括维度(行,列)。 -
Mat
添加构造函数和operator=
或使其不可复制 -
Mat::operator+
和Mat::operator=
检查相等的行,列 - 不再使用时删除内存或
- 使用
std::vector
简化内存管理。
在这里创建了一个更大的例子:https://gist.github.com/KoKuToru/1d23af4bbf0b2bc89893
相关文章:
- 使用赋值运算符重载从类中返回jobject
- 赋值运算符重载和自赋值
- C++ 指针赋值运算符重载(不仅是对象赋值,还有指针赋值)
- 赋值运算符重载在通过指针访问时不调用
- "return *this"赋值运算符重载
- 赋值运算符重载 c++ 的返回值
- 在对类对象的赋值进行链接时获取垃圾值,使用按值返回类对象的赋值运算符重载
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- 复合赋值运算符重载
- 对象的动态内存和赋值运算符重载
- c++中的赋值运算符重载
- c++赋值运算符重载
- 如何通过赋值运算符重载将一个列表复制到另一个列表上?C++
- 赋值运算符重载和无效内存
- 赋值运算符重载 -- 错误 C2440:'==':无法从 'A<T> *' 转换为 'A<T> *const '
- 为什么内存泄漏只发生在赋值运算符重载的情况下,而不是在复制构造函数中,以及复制和交换习惯用法如何解决它
- 内存泄漏,使赋值运算符重载、新建、删除和C++
- C++中的效率和赋值运算符重载
- 赋值运算符重载/检索功能
- 为什么在赋值运算符重载中返回引用