2011-10-02 96 views
6

簡而言之,我的目標是讓foo [bar]返回type1,並且foo [bar] =返回type2。重載多個運算符

我正在用C++編寫一個對象,並且它相當漂亮,但是我只想做一件小事,但它似乎不可能。

我的對象是一個存儲類,所以我使用數組下標來訪問值。我也需要分配,所以我也重載=運算符。然而,這有點不方便,因爲我的類保存的值是第一類對象,所以對於我的數組下標超載,我不能按原樣返回它們。我不得不返回一箇中間類來處理=運算符,但我也想要在沒有額外輸入的情況下檢索該值。

有沒有辦法做到這一點?黑客的方式是可以接受的。

編輯:下面是什麼(應該)再做

#include<cstdio> 
#include<cstdlib> 

class foo{ 
    char* a[100]; 
    foo(){ 
     for(int i = 0; i < 100; i ++) 
      a[i] = 0; 
    } 
    char* operator[] (int location){ 
     return a[location]; 
    } 
    foo& operator[]= (int location, const char* value){ 
     if(a[location] == 0) 
      a[location] = (char*) malloc(strlen(value) + 1); 
     else 
      a[location] = (char*) realloc(a[location], strlen(value) + 1); 
     strcpy(a[location], value); 
    } 
}; 
int main(){ 
    foo bar; 
    bar[20] = "Hello"; 
    printf("bar[20] = %s\n", bar[20]); 
    bar[20] = "Hello There"; 
    printf("bar[20] = %s\n", bar[20]); 
    printf("bar[20][0] = %c\n", bar[20][0]); 
} 

Output: 
bar[20] = Hello 
bar[20] = Hello There 
bar[20][0] = H 

編輯爲例:我想我會嘗試在不同的措辭這一點,但可行的方法。有沒有辦法在引用類時重載返回類型?這樣,如果我有

class foo{ 
    bool a; 
    bool operator /*referenced*/(){ 
     return a 
    } 
    foo& operator=(bool b){ 
     a = b; 
    } 
}; 
int main(){ 
    foo a; 
    a = b; 
    if(a == b) 
     printf("It Works!"); 
} 

這實際上會工作嗎?

+0

可不可以給一些代碼,顯示你想要什麼去做? –

+0

Theres example – Kaslai

回答

5

沒有operator[]=,所以解決方法是編寫一些包裝類,它有兩個關鍵特徵:一個operator=,它接受一個值並將其設置爲父容器,以及一個隱式轉換運算符,該運算符從父容器並返回它。您的operator[]將返回這種包裝。

class foo 
{ 
    friend class wrapper; 
public: 
    class wrapper 
    { 
     friend class foo; 
     foo & _parent; 
     int _index; 

     wrapper(foo & parent, int index) : _index(index), _parent(parent) {} 
    public: 
     wrapper & operator=(const char * value) 
     { 
      if(_parent.a[_index] == 0) 
       _parent.a[_index] = (char*) malloc(strlen(value) + 1); 
      else 
       _parent.a[_index] = (char*) realloc(_parent.a[_index], strlen(value) + 1); 
      strcpy(_parent.a[_index], value); 

      return *this; 
     } 

     operator char *() 
     { 
      return _parent.a[_index]; 
     } 
    }; 

    char* a[100]; 
    foo() 
    { 
     for(int i = 0; i < 100; i ++) 
      a[i] = 0; 
    } 
    wrapper operator[] (int location){ 
     return wrapper(*this, location); 
    } 
}; 

對於第二個問題,好了,你總是可以在foo超載operator==。但也許我誤解了。

+0

好吧,這是我設置的系統,但它只是讓我不得不做額外的輸入。 C++比C更抽象,但我認爲不像抽象的那樣抽象。噢,謝謝你們的投入。 (還有一個答案,但他刪除了他的帖子) – Kaslai

+0

@Aslai:我認爲你的意思是額外打字*你在哪裏使用*。當你想在C++中創建「易於使用」的類時,通常意味着編寫一些非常難看的東西。 –

+0

我的意思是精確的*你在哪裏使用它。*你必須做一個額外的操作符來獲取值,例如cast或(de)引用。 – Kaslai

0

如果你願意使用C++(如您的標籤提示),那麼大部分的工作已經做了你:

class foo: public vector<string> 
{ 
public: 
    foo() 
    { 
    resize(100); 
    } 
}; 

int main() 
{ 
    foo bar; 

    bar[20] = "Hello"; 
    cout << "bar[20] = " << bar[20] << endl; 
    bar[20] = "Hello There"; 
    cout << "bar[20] = " << bar[20] << endl; 
    cout << "bar[20][0] = " << bar[20][0] << endl; 
}