2011-03-05 47 views
0

所以我有這個結構由三個NSPoint結構組成。是否可以像結構的成員一樣處理數組的索引?

typedef struct AOTriangle_ { 
    NSPoint a; 
    NSPoint b; 
    NSPoint c; 
} AOTriangle; 

我想在某些情況下將點作爲a,b,c和其他情況作爲索引引用到數組中。

像這樣,

AOTriangle t; 
t.a = NSMakePoint(0,0); 
t.b = NSMakePoint(3,0); 
t.c = NSMakePoint(0,4); 

for(int i = 0; i < 3; ++i) { 
    t[i].x += 5.0; 
    t[i].y += 5.0; 
} 

這是我已經得到最接近的,但你可以看到它不正是我想要的。 在Objective-C中有這樣做的方法嗎?是不是比我在下面做的類似的事情更好的方式 - 可能與工會?

typedef struct AOTriangle_ { 
    NSPoint a; 
    NSPoint b; 
    NSPoint c; 
} AOTriangle; 


AOTriangle t; 
t.a = NSMakePoint(0,0); 
t.b = NSMakePoint(3,0); 
t.c = NSMakePoint(0,4); 
NSPoint* t = (NSPoint*)&triangle; 
for(int i = 0; i < 3; ++i) { 
    t[i].x += 5.0; 
    t[i].y += 5.0; 
} 

回答

3

是的,您可以使用「union」。我相信聲明會去是這樣的:

typedef struct AOTriangle_ { 
    union { 
     struct { 
      NSPoint a; 
      NSPoint b; 
      NSPoint c; 
     }; 
     NSPoint points[3]; 
    }; 
} AOTriangle; 

一個union基本上是說:「我可以參考這個結構的成員作爲的方式要麼ab,或c,或作爲points[0]points[1],或points[2]「。

而且你會使用這樣的:

AOTriangle t; 
t.a = NSMakePoint(0,0); 
t.b = NSMakePoint(3,0); 
t.c = NSMakePoint(0,4); 
for(int i = 0; i < 3; ++i) { 
    t.points[i].x += 5.0; 
    t.points[i].y += 5.0; 
} 
+0

現工會很少使用?我從來沒有聽說過他們,我非常有信心,我從來沒有見過。 – kubi

+2

它們在C中並不罕見,尤其是低級編程。 – robottobor

+1

@kubi這隻能是做了很少C編程的結果。 –

相關問題