具有 2D 数组添加操作的模板

Templates with Operation for 2d array addition

本文关键字:操作 添加 2D 数组 具有      更新时间:2023-10-16

我有两个 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的数组,我不知道为什么,因为网络上的许多示例都与我的代码相似。

要解决您的问题,您应该

  1. Matrix类中删除temp_arroperator +

  2. 将这一行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;
}

以上应该有助于说明 + 和 += 之间的区别,但您可以对其进行优化。