我想在分配新值之前进行尺寸检查。所以我这样做了:
矩阵.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
谢谢!