通过 [ " " ] 或 [int] 为自定义类C++访问组件

C++ access component via [""] or [int] for custom class

本文关键字:C++ 访问 组件 int 通过 自定义      更新时间:2023-10-16

我注意到C++中的以下内容。

SomeClass obj = SomeClass();
int boo = obj["foo"];

这叫什么?我该怎么做?

示例

class Boo {
public:
     int GetValue (string item) {
          switch (item) {
               case "foo" : return 1;
               case "apple" : return 2;
          }
          return 0;
     }
}
Boo boo = Boo();
int foo = boo.GetValue("foo");
// instead of that I want to be able to do
int foo = boo["foo"];

要使用[],您需要重载operator[]:

class Boo {
public:
     int operator[](string const &item) {
          if (item == "foo")
              return 1;
          if (item == "apple")
              return 2;
          return 0;
     }
};

你可能有兴趣知道std::map已经提供了你想要的东西:

std::map<std::string, int> boo;
boo["foo"] = 1;
boo["apple"] = 2;
int foo = boo["foo"];

明显的区别在于,当/如果您使用它来查找以前未插入的值时,它将插入一个具有该键和值0的新项。

这被称为运算符重载。您需要定义操作员[]的工作方式:

#include <string>
class Boo {
public:
     int operator[] (std::string item) {
          if (item == "foo")  return 1;
          else if (item == "apple") return 2;
          return 0;
     }
};
Boo boo = Boo();
int foo = boo["foo"];

另外,开关变量必须是整型,所以我改为if-else。

您需要重载[]运算符。这里有一个例子(奇怪的是,在Java网站上)。

您想要的是重载下标运算符(operator[]);在你的情况下,你会做:

class Boo {
public:
     int operator[](const string & item) const {
          // you can't use switch with non-integral types
          if(item=="foo")
              return 1;
          else if(item=="apple")
              return 2;
          else
              return 0;
     }
}
Boo boo = Boo();
int foo = boo["foo"];

通常,封装容器的类通过引用返回数据,以允许调用方修改存储的数据;这就是大多数提供operator[]的STL容器所做的。