【发布时间】:2015-06-17 19:48:46
【问题描述】:
我有两个二维数组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 operator + (Matrix tmp)Operator+应该返回一个全新的Matrix,而不是现有的矩阵。返回现有矩阵将是operator +=的工作。 -
@NathanOliver 我看不出三法则与此有什么关系。
-
@juanchopanza 我收回了它。当问题是 Y 时看到 X。
标签: c++ arrays templates operator-overloading