简体   繁体   English

ostream不打印添加两个valarray的结果(使用运算符重载)

[英]ostream not printing the result of adding two valarrays (using operator overloading)

I am still learning about operator overloading and wanted to add two matrices using valarrays, but when i print their addition nothing happens, so here is the code. 我仍在学习运算符重载,并想使用valarrays添加两个矩阵,但是当我打印它们的加法运算时,什么也没有发生,所以这里是代码。

// A structure to store a matrix
struct matrix
{
    valarray<int> data; //valarray that will simulate matrix
    int row, col;
};

matrix operator+(matrix mat1, matrix mat2);

int main() {
    int data1 [] = {1, 2, 3, 4, 5, 6, 7, 8};
    int data2 [] = {13, 233, 3, 4, 5, 6, 7, 8};

    matrix mat1, mat2,ans;
    createMatrix(4, 2, data1, mat1);
    createMatrix(4, 2, data2, mat2);
    cout << mat1 + mat2;
    return 0;
}

//Creating the matrix
void createMatrix(int row, int col, int num[], matrix& mat) {
    mat.row = row;
    mat.col = col;
    mat.data.resize (row * col);
    for (int i = 0; i < row * col; i++)
        mat.data [i] = num [i];
}

ostream& operator<<(ostream& out, matrix mat) {
    for (int i = 0; i < mat.col * mat.row; ++i) {
        out << mat.data[i] << " ";
        if ((i + 1) % mat.col == 0)
            cout << endl;
    }
    return out;
}
// Adding them
matrix operator+(matrix mat1, matrix mat2) {
    matrix ans;
    ans.data.resize(mat1.row * mat1.col);
    for(int i = 0; i < mat1.row * mat1.col; ++i)
        ans.data[i] = (mat1.data[i] + mat2.data[i]);
    return ans;
}

There seem to be no error but when I run this it prints nothing. 似乎没有错误,但是当我运行它时,它什么也不打印。

In operator+ definition you are not setting row and col members for ans object so change your code as follows operator+定义中,您没有为ans对象设置row成员和col成员,因此按如下所示更改代码

matrix operator+(matrix mat1, matrix mat2)
{
    matrix ans;
    ans.data.resize(mat1.row*mat1.col);
    ans.row = mat1.row; // <---
    ans.col = mat1.col; // <---
    for(int i=0;i<mat1.row*mat1.col;++i)
    {
        ans.data[i]=(mat1.data[i]+mat2.data[i]);
    }
    return ans;
}

Without setting these members their values are indeterminate, and probably 如果不设置这些成员,则它们的值是不确定的,并且可能

for(int i=0;i<mat.col*mat.row;++i)

condition i<mat.col*mat.row in operator<< returns false in first iteration, that is why you didn't see any output. 条件i<mat.col*mat.row in operator<<在第一次迭代中返回false,这就是为什么看不到任何输出的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM