0

我想在分配新值之前进行尺寸检查。所以我这样做了:

矩阵.cpp

Matrix& Matrix::operator=(Matrix m){      

    // check dimensions
    if(m_rows != m.m_rows || m_cols != m.m_cols )
        fail();

    thrust::copy(d_data.begin(), d_data.end(), m.d_data.begin() );// gives error if pass in Matrix& m
    return *this;
}

矩阵.h

Matrix& operator=(Matrix m);

测试.cpp

Matrix A, B;
... initialize B as all 1's ...
A = B;       // This works
A = B * 3.0; // Wrong, A = B
B = B * 3.0; // Wrong, B does not change

如果 operator = 没有重载,则正确:

Matrix A, B;
... initialize B as all 1's ...
A = B;       // A is all 1's
A = B * 3.0; // A is all 3's
B = B * 3.0; // B is all 3's

谢谢!

4

3 回答 3

2

你抄错了。

thrust::copy(d_data.begin(), d_data.end(), m.d_data.begin() );

应该:

thrust::copy(m.d_data.begin(), m.d_data.end(), d_data.begin() );
于 2013-09-19T05:16:54.187 回答
0

你的副本是倒退的。您正在从当前对象复制到m按值传递的参数中。当函数返回时,复制的数据与参数一起被销毁,因此它实际上什么都不做。

const &如果您传递的是规范参数而不是值,这将被显示为 const 正确性错误。

于 2013-09-19T05:17:02.633 回答
0

您可以从中查看,这可能会有所帮助:

http://www.programmingtunes.com/overloading-assignment-operator-in-c/

这是我得到解决方案的博客,你也可以找到你的答案

于 2013-09-27T16:34:21.767 回答