如何从函数运算符(x,y)返回向量元素的引用

how to return a reference of a vector element from a function operator(x,y)

本文关键字:返回 向量 元素 引用 函数 运算符      更新时间:2023-10-16

我有一个类模板,它包含一个向量T作为受保护的成员变量。我想重载运算符(),以便它在y行和x列中返回向量元素的引用。

当我将operator()函数声明为:时

template <class T>
T & ArrayT<T>::operator()(unsigned int x, unsigned int y)const{
return buffer[y*width + x];
}

我得到C2440错误:"return":无法从"const_Ty"转换为"T&">

如果我将运算符函数声明为:

template <class T>
const T & ArrayT<T>::operator()(unsigned int x, unsigned int y)const{
return buffer[y*width + x];
}

然后我的代码编译,但如果例如我创建了一个派生的templeted类,其中T是float,并且我写(obj是派生类的对象,具有float的成员变量向量):

float f=obj(i,j); 
f=pow(f,2);

然后似乎什么也没发生。向量内位置i,j的浮点值不会改变,所以假设我真的不处理引用,因为如果引用是由运算符()返回的,那么上面的行应该会改变位置(i,j)的元素,对吗?

我是c++的新手,我知道我可能在这里犯了一些非常愚蠢的错误,但请提供任何帮助都是受欢迎的。

声明不带const的运算符,如下所示:

template <class T>
T & ArrayT<T>::operator()(unsigned int x, unsigned int y) {
return buffer[y*width + x];
}

访问元素如下:

float & f = obj(i, j);

我们通常提供常量运算符(就像OP一样):

template <class T>
const T & ArrayT<T>::operator()(unsigned int x, unsigned int y) const {
return buffer[y*width + x];
}
float f = obj(i, j);          // f is copy of current i,j value 
const float & f = obj(i, j);  // f references i,j value, i.e. we can
// observe future modifications