Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从函数运算符(x,y)返回向量元素的引用_C++_Vector_Reference_Operator Keyword - Fatal编程技术网

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

C++ 如何从函数运算符(x,y)返回向量元素的引用,c++,vector,reference,operator-keyword,C++,Vector,Reference,Operator Keyword,我有一个类模板,它包含一个T向量作为受保护的成员变量。我想重载操作符(),以便它返回y行和x列中向量元素的引用 当我将运算符()函数声明为: template <class T> T & ArrayT<T>::operator()(unsigned int x, unsigned int y)const{ return buffer[y*width + x]; } template <class T> const T & ArrayT

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

当我将运算符()函数声明为:

template <class T>
T & ArrayT<T>::operator()(unsigned int x, unsigned int y)const{
    return buffer[y*width + x];
}
template <class T>
const T & ArrayT<T>::operator()(unsigned int x, unsigned int y)const{
    return buffer[y*width + x];
}
然后什么也没发生。向量中i,j位置的浮点没有改变,所以假设我没有真正处理引用,因为如果操作符()返回了引用,那么上面的行应该会改变(i,j)位置的元素,对吗


<>我对C++是新的,我知道我可能在这里犯了一些非常愚蠢的错误,但是请任何形式的帮助都是受欢迎的。< /p> < p>声明没有“代码> 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一样):

模板
常量T&ArrayT::operator()(无符号整数x,无符号整数y)常量{
返回缓冲区[y*宽度+x];
}
浮点数f=obj(i,j);//f是当前i,j值的副本
常量浮点&f=obj(i,j);//f参考i,j值,即我们可以
//观察将来的修改

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

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

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

模板
常量T&ArrayT::operator()(无符号整数x,无符号整数y)常量{
返回缓冲区[y*宽度+x];
}
浮点数f=obj(i,j);//f是当前i,j值的副本
常量浮点&f=obj(i,j);//f参考i,j值,即我们可以
//观察将来的修改

您应该删除操作员声明中的2
const
,并使用
float&f=obj(i,j)。但请注意,您的设计方法并不好。考虑使用SETER函数修改受保护向量的元素。我考虑制作一个SETER函数,并尝试从操作符声明中删除const。我的问题是,使用操作符的对象将是const,因此setter函数在这种情况下不适用,并且从操作符声明中删除const会使操作符在const对象的情况下不适用。我可以尝试其他方法吗?修改常量对象没有多大意义,是吗?您应该删除运算符声明中的2
const
,并使用
float&f=obj(i,j)。但请注意,您的设计方法并不好。考虑使用SETER函数修改受保护向量的元素。我考虑制作一个SETER函数,并尝试从操作符声明中删除const。我的问题是,使用操作符的对象将是const,因此setter函数在这种情况下不适用,并且从操作符声明中删除const会使操作符在const对象的情况下不适用。我可以尝试其他方法吗?修改常量对象没有多大意义,是吗?通常,我们实现两个版本,常量和非常量。通常,我们实现两个版本,常量和非常量。