模板类c ++的赋值运算符

时间:2015-06-01 16:57:50

标签: c++ operator-overloading

永远不会调用赋值运算符重载。

在1.的主文件中,复制构造函数被调用,在2.中,首先调用是operator + then operator *然后调用默认赋值运算符。

出现这个问题的原因是什么?

template<int r, int c, class F = int>
class Matrix {

public:

    Matrix(){
        int i, j;
        data = new F[(r*c)];
        for (i = 0; i < c; i++){
            for (j = 0; j < r; j++){
                data[j + (i*c)] = 0;
            }
        }
    }
    ...

    Matrix(const Matrix& a){
        int i=r, j=c;
        data = new F[(r*c)];
        for(i = 0; i < r; i++){
            for(j = 0; j < c; j++){
                data[j+(i*c)] = a.data[j+(i*c)];
            }
        }
    }
    **Matrix operator=(const Matrix a){
        int i, j;
        if (data != NULL){
            delete data;
            data = NULL;
        }
        data = new F[(r*c)];
        for(i = 0; i < r; i++){
            for(j = 0; j < c; j++){
                data[j+(i*c)] = a.data[j+(i*c)];
            }
        }
        return *this;
    }**
    friend Matrix operator+( Matrix<r, c, F>& a, int b){
        Matrix<r, c, F> temp;
        int i, j;
        for(i = 0; i < r; i++){
            for(j = 0; j < c; j++){
                temp.data[j+(i*c)] = a.data[j+(i*c)] + b;
            }
        }
        return temp;
    }
    Matrix operator*(const int a){
        Matrix <r, c, F> temp(*this);
        int i, j;
        for(i = 0; i < r; i++){
            for(j = 0; j < c; j++){
                temp.data[j+(i*c)] *= a;
            }
        }
        return temp;
    }
   ...


    ~Matrix(){
        delete[] data;
        data = NULL;
    }

private:
    F *data;


};



int main( ) {
    ...

    Matrix<4, 4> identity(1);
    std::cout << identity << std::endl;

    1.**Matrix<4, 4> res = identity;**

    Matrix<4, 4> identity_2(1);
    std::cout << identity _2<< std::endl;

    2.**Matrix<4, 4> res_2 = (identity_2 + 2) * 3;**
...

1 个答案:

答案 0 :(得分:1)

friend Matrix operator+( Matrix<r, c, F>& a, int b){
    Matrix<r, c, F> temp;
    int i, j;
    for(i = 0; i < r; i++){
        for(j = 0; j < c; j++){
            temp.data[j+(i*c)] = a.data[j+(i*c)] + b;
        }
    }
    return temp;
}

此代码混淆了运算符的非成员和成员语法。

friend Matrix operator+( Matrix<r, c, F>& a, int b);

表示“有一个非成员函数可以访问我的内部”。但是你定义的是一个成员函数,它应该有语法

Matrix operator+(int b) {

由于隐含this,因为它是一个成员函数。 See this answer以讨论细微差别为例。

同样,您的赋值运算符也不正确。

Matrix& operator=(const Matrix& a) {

是最常见的形式,虽然参数的格式可以更改,但您需要返回返回值的引用。