c++ - 绑定到时间。l/r 值
问题描述
在从这个 S/O答案编译以下代码时,由于绑定问题,我不断收到错误。
class my_matrix {
std::vector<std::vector<bool> >m;
public:
my_matrix(unsigned int x, unsigned int y) {
m.resize(x, std::vector<bool>(y,false));
}
class matrix_row {
std::vector<bool>& row;
public:
matrix_row(std::vector<bool>& r) : row(r) {
}
bool& operator[](unsigned int y) {
return row.at(y);
}
};
matrix_row& operator[](unsigned int x) {
return matrix_row(m.at(x));
}
};
// Example usage
my_matrix mm(100,100);
mm[10][10] = true;
这是报告
m.cpp:16:14: error: non-const lvalue reference to type 'bool' cannot bind to a
temporary of type 'reference' (aka '__bit_reference<std::__1::vector<bool,
std::__1::allocator<bool> > >')
return row.at(y);
^~~~~~~~~
m.cpp:20:12: error: non-const lvalue reference to type 'my_matrix::matrix_row'
cannot bind to a temporary of type 'my_matrix::matrix_row'
return matrix_row(m.at(x));
^~~~~~~~~~~~~~~~~~~
对此进行研究后,我意识到 Bool 向量与普通的 C++ 向量不同。因此,我可以通过将其更改为 int 向量来避免第一个错误。
最后一行的第二个错误更令人困惑。我已经看过这个问题,但我仍然不知道该怎么做。
** 编辑 **
鉴于答案/评论,我觉得这样的事情应该可行,
matrix_row& operator[](unsigned int x) {
std::vector<int> e = m.at(x);
matrix_row f = matrix_row(e);
return f;
它不是。这似乎会创建带有内存的变量(e 和 f)?
解决方案
您正在尝试将非常量左值引用绑定到右值。那是不可能的。
请注意,尽管将 const 引用或非 const 右值引用绑定到右值在语法上是正确的,但这是错误的,因为您创建的临时对象在函数返回后停止存在,因此对临时对象的引用不是有用。
您可能应该从函数返回一个对象,而不是一个引用。
编辑:
不,您的新建议也不起作用,原因仍然相同。e
一旦函数返回,本地对象就会停止存在,因此对它的引用是没有用的。
推荐阅读
- php - 使用 PHP 加载 .env 文件
- c# - 统一。Input.MousePosition 返回的坐标对于屏幕来说太大了
- python - 创建一个python类以返回数据库连接
- python - 通过循环旧元组创建新元组的更有效方法
- azure-devops - 如果主机启动,则在组中列出的任何一台主机上执行播放
- django - 使用 drf-nested-routers 时 Django Rest Framework“找不到页面”错误
- vue.js - 为什么我的伴生对象会与我的目标一起更新?
- node.js - 每个游戏的 NodeJs setTimeout 或循环每个游戏的一个 setInterval
- python - 将过去的日期值分组到列表中
- javascript - 从 Ionic 中的 API 访问嵌套数组