簡而言之,我的目標是讓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!");
}
這實際上會工作嗎?
可不可以給一些代碼,顯示你想要什麼去做? –
Theres example – Kaslai