[英]c++ overloading the [] operator without a class
我創建了一個結構:
struct a{
int a1;
int a2;
int a3;
};
有什么方法可以創建一個 function ,其中a[1]
將以與我可以通過數組相同的方式訪問a1
?
編輯,我已經粘貼了我實際做的部分:
struct lipid{
particle mainPart;
bead * head;
bead * body;
bead * tail;
vec direction;
bead * operator[](int index){
switch(index){
case 0: return head;
case 1: return body;
case 2: return tail;
default: return body;
}
}
};
bead 和particle 是我創建的另一個結構。 它有效...謝謝
Stroustrup 的“C++ 編程語言”第 11.8 節(運算符重載、下標)的最后一行:
'An operator []() must be a member function.'
所以,不,這在 C++ 中是不可能的。
(雖然結構當然是struct
中的class
,但我假設您的意思是您希望struct a
保持為 POD)
正如 delnan 所指出的,您可以在結構上使用方法,就像類一樣。
所以:
struct a{
int a1;
int a2;
int a3;
int &operator[]( int i ){
switch(i){
case 1: return a1;
case 2: return a2;
case 3: return a3;
default: return -1
}
}
};
由於operator [] must be a member function
,正如其他人所指出的那樣,您不能這樣做。
但是我想出了以下名為subscriptable
的包裝器 class ,它可以幫助您模擬它:
class subscriptable
{
A & a;
public:
subscriptable(A & a) : a(a) {}
subscriptable(const subscriptable & s) : a(s.a) {}
int & operator[](int i)
{
if ( i < 0 || i > 2 ) throw "index out of range";
else if ( i == 0 ) return a.a1;
else if ( i == 1 ) return a.a2;
else return a.a3;
}
operator A & () { return a; }
};
void print(A & a)
{
subscriptable s = a; //a implicitly converts to subscriptable
for ( int i = 0 ; i < 3 ; i++ )
std::cout << s[i] << std::endl;
}
int main()
{
A a;
subscriptable s = a; //a implicitly converts to subscriptable
for ( int i = 0 ; i < 3 ; i++ )
s[i] = (i + 1) * 100;
print(s); //s implicitly converts to A
return 0;
}
Output:
100
200
300
好吧,如果必須的話,您可以與工會一起解決它,盡管您可能會不贊成:
union
{
struct
{
int a1;
int a2;
int a3;
};
int a[]; // may need compiler-specific tweaking
};
請注意,並非所有編譯器都支持int a[]
,您可能必須編寫int a[0]
甚至int a[3]
,具體取決於編譯器/語言方言。
讓我們假設struct a
在某個庫中並且您無法更改它,因為否則您將采用@delnan 的typedef
建議( typedef int a[3]
)。
如果該結構未以多態方式使用,您可以濫用 inheritance 並自己添加運算符:
struct a_with_brackets : public a
{
int& operator[](int index)
{
switch(index)
{
case 1 : return a1;
case 2 : return a2;
case 3 : return a3;
}
}
};
struct a{
int a1;
int a2;
int a3;
int & operator[]( int i ) {
if ( i == 0 ) {
return a1;
}
else if ( i == 1 ) {
return a2;
}
else if ( i == 2 ) {
return a3;
}
else {
throw "index error";
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.