【问题标题】:how to return a reference of a vector element from a function operator(x,y)如何从函数运算符(x,y)返回向量元素的引用
【发布时间】:2019-05-27 03:50:08
【问题描述】:

我有一个类模板,其中包含一个 T 向量作为受保护的成员变量。我想重载 operator() 以便它返回第 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];
}

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

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

然后似乎什么都没有发生。向量内 i,j 位置的浮点数没有改变,因此假设我没有真正处理引用,因为如果操作符 () 返回了引用,则上述行应更改位置 (i,j) 中的元素对吧?

我是 C++ 新手,我知道我在这里可能会犯一些非常愚蠢的错误,但欢迎任何形式的帮助。

【问题讨论】:

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

标签: c++ vector reference operator-keyword


【解决方案1】:

声明没有const的操作符,像这样:

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

像这样访问元素:

float & f = obj(i, j);

我们通常提供 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

【讨论】:

  • 通常,我们实现两个版本,const 和 non const。
猜你喜欢
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2021-07-24
相关资源
最近更新 更多