函数返回对向量元素的引用

jir*_*ira 5 c++ reference stdvector

我无法弄清楚如何返回对vector元素的引用.[]和at()返回引用,不是吗?

但是当我尝试以下内容时,它将无法编译.

我使用的是Visual C++,它 不能将'const float'转换为'float& error.

T& GetElement(size_t x) const {
    return _vector.at(x);
}
Run Code Online (Sandbox Code Playgroud)

GetElement是一个方法,_vector是一个成员变量.

das*_*ght 8

这不会编译,因为您试图返回对向量元素的非常量引用,该元素本身就是这样const.

向量的原因const是声明了您的成员函数const:

T& GetElement(size_t x) const // <<== Here
Run Code Online (Sandbox Code Playgroud)

const-ness标记会传播到所有成员,包括_vector.

要解决此问题,请添加const要返回的引用类型(演示).


Jos*_*eld 5

您没有显示错误,但是作为一个猜测,它看起来像是_vector一个成员(来自_给定的前缀),并且您处于const成员函数中,因此at将返回const引用。因此,您可能需要:

const T& GetElement(size_t x) const {
    return _vector.at(x);
}
Run Code Online (Sandbox Code Playgroud)