2012-02-16 17 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。

相關問題