简体   繁体   English

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

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

I have a class template which contains a vector of T as a protected member variable. 我有一个类模板,其中包含T的向量作为受保护的成员变量。 I want to overload the operator() so that it returns a reference of the vector's element in line y and column x. 我想重载operator(),以便它在y行和x列中返回向量元素的引用。

When i declare the operator() function as: 当我将operator()函数声明为:

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

i get C2440 error: 'return': cannot convert from 'const_Ty' to 'T&' 我收到C2440错误:“返回”:无法从“ const_Ty”转换为“ T&”

If i declare the operator function as: 如果我将运算符声明为:

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

then my code compiles but if for example i create a derived templeted class where T is float and i write (obj is an object of the derived class with a member variable vector of floats): 然后我的代码会编译,但是例如,如果我创建一个派生的模板化类,其中T为float并编写(obj是该派生类的对象,其成员变量向量为floats):

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

then nothing seems to happen. 那么似乎什么也没发生。 The float in the position i,j inside the vector does not change so assume that i dont really work on a reference, because if a reference was returned by the operator () the above lines should change the element in position (i,j) right? 向量中位置i,j处的浮点数不会改变,因此假设我对引用没有实际作用,因为如果操作员()返回了引用,则上述几行应更改位置(i,j)中的元素对?

I am new to c++ and i understand i might be doing some very silly mistakes here, but please any kind of help woulb be welcome. 我是C ++的新手,我知道我在这里可能犯了一些非常愚蠢的错误,但是请提供任何帮助。

Declare the operator without const , like this: 声明不带const的运算符,如下所示:

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

Access elements like this: 访问这样的元素:

float & f = obj(i, j);

We usually provide const operator (as OP did): 我们通常提供const运算子(就像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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM