C++ 中的对象如何找到右值引用(未命名值)? [重复]

问题描述 投票:0回答:1

我有一个名为 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;
}
};

编译器不允许我同时重载。

c++ c++11 operator-overloading rvalue-reference rvalue
1个回答
1
投票

您可以使用 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)
看起来很不言自明)

© www.soinside.com 2019 - 2024. All rights reserved.