【发布时间】:2018-09-17 14:57:31
【问题描述】:
从这个 S/O answer 编译以下代码时,由于绑定问题,我不断收到错误消息。
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 向量来避免第一个错误。
最后一行的第二个错误更令人困惑。我看过这个question,但我仍然不知道该怎么做。
** 编辑 **
鉴于答案/评论,我觉得这样的事情应该可行,
matrix_row& operator[](unsigned int x) {
std::vector<int> e = m.at(x);
matrix_row f = matrix_row(e);
return f;
它没有。这似乎会创建带有内存的变量(e 和 f)?
【问题讨论】:
-
matrix_row(m.at(x))是一个临时的,由向量元素构成。您正在尝试返回一个左值引用 - 它不能引用一个临时的。由于vector<bool>不起作用的完全相同的原因,它不起作用 - 您正在返回一个代理对象,而不是对实际元素的引用。 -
@IgorTandetnik 谢谢你的评论,真的很有帮助!据我了解,我现在需要创建一个分配了一些内存的变量,然后在函数中返回它?
-
按值返回
matrix_row,或返回std::vector<bool>引用。你不能同时拥有它 -
@IgorTandetnik 谢谢,所以我删除了函数定义中的
&,现在出现以下错误,ld: can't open output file for writing: m./m, errno=2 for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)any idea? -
我的猜测是,您尝试构建的可执行文件仍在运行,可能来自之前的实验。