c++ - 如何通过指针简化重载下标运算符的使用?

标签 c++ operator-overloading subscript

我有一个 Foo 类,它封装了对 vector 的访问并通过下标运算符提供对它的访问:

typedef int* IntPtr; 

class Foo {
   std::vector<IntPtr> bars;
   IntPtr& operator[](size_t idx) {
      return bars[idx];
   }
};

Bar 类中,我想使用 Foo。虽然解决方案 1 有效,但相当不方便。我更喜欢解决方案 2 之类的东西。显然,方法调用(即使它返回一个左值)不能被赋值,尽管方法调用除了解决方案 1 之外什么都不做。

class Bar {
   Foo *foo; //some initialization

   IntPtr helper(size_t idx) {
      return (*foo)[idx];
   }

   void barfoo() {
      size_t baz = 1;
      IntPtr qux;

      //solution 1
      qux = (*foo)[baz];  //works
      (*foo)[baz] = &1;    //works

      //solution 2
      qux = helper(baz);  //works
      helper(baz) = &1;    //does not work: "expression is not assignable"
   }     
};

问题:如何简化重载下标运算符的使用?

编辑:将使用的类型从 int 更改为 int*。抱歉,我在创建示例时搞砸了。

我猜问题是因为扭曲的int*&

最佳答案

最好的方法是编写一个常规方法,例如 Foo::at(size_t idx),提供与您的运算符相同的功能。 请注意,STL 执行相同的操作(只需看一下 std::vector)。 然后您可以简单地调用 foo->at(baz);。为避免冗余,您可以更改 operator[] 的实现:

int& operator[](size_t idx) {
    return at(idx);
}

在您的代码段中,您无法为返回值分配值,因为您忘记返回引用。

不是很好,但替代方案是 foo->operator[](baz);,但我强烈建议您编写如此丑陋的代码。

关于c++ - 如何通过指针简化重载下标运算符的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20247799/

相关文章:

r - 如何从 kable() 为表中的名称添加下标?

c++ - 重载赋值运算符 带下标运算符

c++ - 如何对用户定义类型的 CArray 进行排序?

c++ - 将文本插入文件仅有效一次

c++ - 如何阅读 MSDN 并申请?

c++ - "Id returned 1 exit status"错误 C++

c++ - 数值 vector 运算符重载+右值引用参数

c++重载和覆盖operator +

C++ << 运算符重载和 Arduino 模板

ios - swift 数组 : subscript with IndexPath - unable to mutate