如何从函数运算符(x,y)返回向量元素的引用
how to return a reference of a vector element from a function operator(x,y)
我有一个类模板,它包含一个向量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
相关文章:
- 如何返回向量的常量引用?
- 如何在C++中返回向量的从零开始的索引
- 当函数返回C++向量实例时,它正在运行
- 从函数返回向量以打印内容
- 返回向量的单个索引值
- 为什么我不能返回向量<向量<int>>(进程返回 -1073741819 (0xC0000005))
- 返回向量元素的 l 值的正确方法是什么?
- 为什么通过引用返回向量比通过移动返回要快得多?
- 返回向量 C++ 上的递归
- C++ std::find() 寻址返回向量的类函数时的意外行为
- 如何在返回向量中访问系数
- C++ 函数返回向量中最小的正整数
- 查找并将指针返回向量中的对象
- getCompatibleComponent返回向量错误
- 如何从 JNI 返回向量<向量<float>>?
- 为什么下面的代码返回向量大小为 10
- 从函数返回向量时C++中止(核心转储)
- 如何正确地将向量<int>转换为空隙*并返回向量<int>?
- 接口 PTR 的返回向量C++
- C++ cv::Mat 返回向量的<rectangle>线程异步