繁体   English   中英

如何从 std::vector 返回 object 的引用<std::vector<> &gt; </std::vector<>

[英]how to return a reference of an object from std::vector<std::vector<>>

就像标题一样,这是一段代码:

class matrix{
    std::vector<std::vector<bool>> base;
    std::pair<int, int> size;
public:
    matrix(int x, int y){
        size.first = x; size.second = y;
        std::vector<std::vector<bool>> b(x, std::vector<bool>(y));
        base = b;
    }
    bool& operator ()(int x, int y) const {
        if(x < 0 || y < 0 || x >= size.first || y >= size.second){outOfBounds ex; throw ex;}
        return base[x][y];
    }
    /*and more that is unrelated to the question*/
};

错误在bool& operator(...)中,如下所示:

cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type‘std::vector<bool>::const_reference’ {aka ‘bool’}
   30 |                 return base[x][y];

在代码中,向量(矩阵)的大小不会改变

我也用 int 替换了 bool 和它同样的问题,不能从int转换为int&

function 不能为 const,这样可以改变引用的值

bool& operator ()(int x, int y) const {

末尾的const表示这是一个常量class 方法,并且this是常量。

return base[x][y];

这里面的一切都是不变的。 包括这个。 因此,此运算符重载的返回值应该是const bool &而不是bool &

如果在理解了这一点之后,您返回 go 并重新阅读编译器的错误消息,它现在对您来说应该很有意义,因为这正是您的编译器告诉您的。

或者,您可以从重载的运算符声明中删除const ,并返回一个bool & ,这取决于您。

但是,你会遇到另一个特殊的问题: std::vector<bool>并不是真正的布尔向量,而是一些非常奇怪的东西。

因此,最终的解决方案可能是简单地将返回值声明为auto & ,并让编译器为您解决。 ...你真的不想知道它到底是什么。

暂无
暂无

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

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