2012-02-16 28 views
1

我注意到了类似于C++中的内容。通过[“”]或[int]为自定义类别提供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"]; 

回答

2

要使用[],你会超载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.

+1

您无法打开字符串。 – Mankarse 2012-02-16 01:56:34

+0

@Mankarse:好点。固定。谢谢。 – 2012-02-16 02:06:55

1

你想要的是重载下标操作符(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容器所做的。

2

这被称为运算符重载。 您需要定义操作[]是如何工作的:

#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。

相关问题