简体   繁体   English

具有函数运算符的C ++数组类,用于赋值

[英]C++ array class with function operator for assignment

I want to write my own 2d array class. 我想编写自己的2d数组类。 I want the class to be able to assign a value to an element like this. 我希望类能够为这样的元素分配一个值。

a(0,0) = 1

I know this must be possible because I can do it with the matrix classes from blaze and eigen . 我知道这是有可能的,因为我可以使用blazeeigen的矩阵类来做到这一点。 My first idea was to overload the function operator () , which already works great to access the elements. 我的第一个想法是重载函数operator () ,该函数已经很好地访问元素了。 When I try to assign a value with a(0,2) = 0; 当我尝试分配a a(0,2) = 0; I get a compiler error. 我收到编译器错误。

lvalue required as left operand of assingment

What operator do I have to overload that the assignment also works? 我必须让哪个运算符重载该分配也可以正常工作?

You need to build a function with this prototype: 您需要使用此原型构建一个函数:

T& operator()(std::size_t, std::size_t);

Where T is your element type. 其中T是您的元素类型。 This function needs to return a reference to an element in the array. 此函数需要返回对数组中元素的引用 This allows you to modify the value of the element via that reference in the caller. 这允许您通过调用者中的引用来修改元素的值。

As well as the above, you ought to provide the function 和上面一样,您应该提供功能

const T& operator()(std::size_t, std::size_t) const;

for read-only element access. 用于只读元素访问。 I've rather dogmatically insisted on std::size_t for your indexing. 我相当教条地坚持使用std::size_t进行索引。 In reality, you might want a typedef of your own to stand in for the index type. 实际上,您可能希望自己的typedef代表索引类型。

You need to provide two overloads - one const and another one not, returning a reference. 您需要提供两个重载-一个const ,另一个不重载,返回一个引用。 For example: 例如:

template <typename TVal> class val {
  std::map<int, TVal> values;

public:
  // the distinction is between a const version ...
  TVal operator()(int key) const {
    auto found = values.find(key);
    if (found != values.end())
      return found->second;

    return TVal();
  }

  // ... and a non-const, returning a reference
  TVal& operator()(int key) {
   return values[key];
  }
};

and then you can use it as follows: 然后可以按以下方式使用它:

val<int> v;
v(1) = 41;
v(1)++;
std::cout << v(1) << std::endl; // -> 42
std::cout << v(2) << std::endl; // -> 0

Please post the compile-error, for others to see and precisely answer it. 请发布编译错误,以供其他人查看并准确解决。

Having said that, I am pretty sure that it is because you are not returning a reference from your operator. 话虽如此,我很确定这是因为您没有从操作员那里返回参考。

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

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