Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++类访问组件通过[“]或[INT]自定义类 我注意到了一些类似C++中的内容。 SomeClass obj = SomeClass(); int boo = obj["foo"];_C++ - Fatal编程技术网

C++类访问组件通过[“]或[INT]自定义类 我注意到了一些类似C++中的内容。 SomeClass obj = SomeClass(); int boo = obj["foo"];

C++类访问组件通过[“]或[INT]自定义类 我注意到了一些类似C++中的内容。 SomeClass obj = SomeClass(); int boo = obj["foo"];,c++,C++,这叫什么?我怎么做 范例 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.GetVal

这叫什么?我怎么做

范例

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"];

您需要重载[]运算符。奇怪的是,在Java站点上。

您需要重载[]操作符。奇怪的是,在Java站点上。

您想要的是重载下标操作符[];在您的情况下,您会:

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"];

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

您需要的是重载下标运算符[];在您的情况下,您会:

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"];
封装容器的类通常通过引用返回数据,以允许调用方修改存储的数据;这就是大多数提供运算符[]的STL容器所做的。

要使用[],您需要重载运算符[]:

您可能有兴趣知道std::map已经提供了您想要的内容:

std::map<std::string, int> boo;

boo["foo"] = 1;
boo["apple"] = 2;

int foo = boo["foo"];
明显的区别是,当/如果您使用该键查找以前未插入的值时,它将插入一个具有该键和值0的新项。

要使用[],您需要重载运算符[]:

您可能有兴趣知道std::map已经提供了您想要的内容:

std::map<std::string, int> boo;

boo["foo"] = 1;
boo["apple"] = 2;

int foo = boo["foo"];

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

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


此外,开关变量必须具有整数类型,因此我改为if-else。

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


此外,switch变量必须具有整数类型,因此我改为if-else。

您不能打开字符串。您不能打开字符串。