具有 2D 数组添加操作的模板
Templates with Operation for 2d array addition
我有两个 2d 数组arr1
这属于对象 s1
arr2
这属于对象 s2
我想存储对象s3
的添加。经过大量的搜索和试验this
,这是我的代码:
#include <iostream>
#include <sstream>
using namespace std;
template <class T>
class Matrix
{
private:
T arr[2][2];
T temp_arr[2][2];
public:
Matrix();
void display();
void seter(T _var[2][2]);
Matrix operator + (Matrix tmp)
{
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
this->temp_arr[i][j]=arr[i][j]+tmp.arr[i][j];
return *this;
}
};
template<class T>
Matrix<T>::Matrix()
{
}
template<class T>
void Matrix<T>::display()
{
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
cout<<endl<<arr[i][j];
}
template<class T>
void Matrix<T>::seter(T _var[2][2])
{
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
arr[i][j]=_var[i][j];
}
int main()
{
double arr1[2][2];
double arr2[2][2];
double x=2.5,y=3.5;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
arr1[i][j]=x++;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
arr2[i][j]=y++;
Matrix<double> s1;
Matrix<double> s2;
Matrix<double> s3;
s1.seter(arr1);
s2.seter(arr2);
s3=s1+s2;
s1.display();
cout<<endl;
s2.display();
cout<<endl;
s3.display();
return 0;
}
它仍然返回对象s1
的数组,我不知道为什么,因为网络上的许多示例都与我的代码相似。
要解决您的问题,您应该
-
从
Matrix
类中删除temp_arr
并operator +
。 -
将这一行
operator +
从 this:this->temp_arr[i][j]=arr[i][j]+tmp.arr[i][j];
更改为 this:arr[i][j] += tmp.arr[i][j];
无需在实现中temp_arr
。
下面是使用上述更改的实时示例: http://ideone.com/lMF3kT
另一个问题是您在调用 operator +
时更改了原始Matrix
对象。 这是违反直觉的,因为+
不应该更改原始对象,而是应该返回一个新对象。
要解决此问题,您可以将代码(修复后)移出operator +
并将其移动到 operator +=
。
Matrix& operator += (const Matrix& tmp)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
arr[i][j] += tmp.arr[i][j];
return *this;
}
请注意,我们返回原始对象作为引用。 现在,我们可以在operator +=
方面实现operator +
:
Matrix operator + (const Matrix& tmp)
{
Matrix temp(*this);
return temp += tmp;
}
编辑:
做了参数常量引用。
您不应该将 temp_arr
作为类成员,而是在 const 运算符中使用临时实例并将其返回到堆栈中
此外,由于人们应该能够添加const
实例,因此请将operator +
设置为const
成员函数:
Matrix operator + (const Matrix& tmp) const
{
Matrix ret(*this);
ret+=tmp;
return ret;
}
以上应该有助于说明 + 和 += 之间的区别,但您可以对其进行优化。
相关文章:
- 堆栈粉碎 在我在代码中添加新变量以及一些操作后C++检测到
- 宏如何在Tensorflow中添加新的操作时"REGISTER_OP("ZeroOut")
- 当我尝试在 tensorflow 中添加一个新操作时如何 #include "include/libxsmm.h"?
- 如何使用阻止套接字 API 添加消息发送操作 (smtp) 的进度?
- 静态断言添加操作是否可用
- 在窗口中的张量流中添加操作
- QT从Qmenu删除操作,以后再添加
- 如何添加到由QtConcurrent::map操作的QStringList中?
- 在范围内添加位操作和转换式的枚举 - 圣诞节探索
- 如何在服务exe中添加失败操作
- C++ 用于添加操作的线程安全
- 将操作码添加到现有二进制文件所需的内容
- 向QListWidget添加操作
- 我正在寻找一种在从模型中删除并重新添加修改后的可提取对象后操作 iloextract 对象的方法
- 在Model上添加操作而不向Model中添加代码
- Qt5无法识别快捷方式,除非将操作添加到工具栏中
- 添加C++前缀是否"const"硬件级别执行任何不同操作,或者只是对编码人员的保护?
- c++添加操作菜单
- 具有 2D 数组添加操作的模板
- 添加叠加/操作使用AVFoundation为iPhone