我有一个名为 Matrix 的类。我想要重载运算符!返回矩阵的转置。 当主矩阵是未命名的对象时,我更喜欢使用它分配的内存来构造转置矩阵,否则使用新矩阵。我该怎么做。(我们假设矩阵的行数和列数相等)
class Matrix {
// ...
/* transpose of a unnamed matrix */
Matrix&& operator !()
{
for (int i = 0; i < rows_; ++i)
for (int j = 0; j < cols_; ++j)
std::swap(data[i][j],data[j][i]);
return std::move(*this);
}
/* transpose of a matrix that is not rvalue refrence */
Matrix operator !()const
{
Matrix ret(cols_, rows_);
for (int i = 0; i < rows_; ++i)
for (int j = 0; j < cols_; ++j)
ret.data[j][i] = data[i][j];
return temp;
}
};
编译器不允许我同时重载。
您可以使用 ref-qualifiers 来做到这一点:
// (Also I would recommend you return by value here to prevent dangling references. You can still move from *this.)
Matrix&& operator !() && { // Called on rvalues
// ...
}
Matrix operator !() const& { // Called on lvalues (and const rvalues)
// ...
}
您也可以将其编写为自由函数:
// (Or have these outside the class)
friend Matrix&& operator!(Matrix&& mat) {
// ...
}
friend Matrix operator!(const Matrix& mat) {
// ...
}
// You can also take by value instead so the move or copy is at the call site
friend Matrix operator!(Matrix mat) {
// ... (in place transpose mat)
}
正如人们在评论中指出的那样,
!x
通常意味着!static_cast<bool>(x)
,并且根据最小惊喜原则,你可能不应该让它做不同的事情。
考虑
operator~
,或好友功能 T
(T(mat)
看起来很不言自明)