extern void drawshape(__strong id shape[],int num);
int main(int argc, const char * argv[])
{
id shape[3]; //創建一個數組,存放具體的圖形對象
ShapEgg *egg = [[ShapEgg alloc]init]; //對象的初始化,先分配內存,在調用init方法初始化
//把egg對象賦給shape數組的第一個元素
shape[0] = egg;
//創建一個circle對象
Circle *circle = [[Circle alloc]init];
shape[1] = circle;
Rectangle *rectangle = [[Rectangle alloc]init];
shape[2] = rectangle;
drawshape(shape,3);
return 0
}
void drawshape(__strong id shape[],int num)
{
for(int i = 0; i < num; i++)
{
[shape[i] draw];
}
}
定義一個Circle類
@interface Circle : NSObject
{
ShapColor fillColor; // 定義成員變量或者實例變量
ShapRect bounds;
}
-(Circle *)init; //對象方法(重構init方法)
-(void)draw;
@end //end of Circle
實現代碼
@implementation Circle
-(Circle *)init
{
if (self = [super init]) { //super
ShapRect rect = {1,32,35,56};
bounds = rect;
fillColor = kRedColor;
}
return self;
}
-(void)draw
{
NSLog(@"Circle is draw at (%d,%d,%d,%d) in %@",bounds.x,bounds.y,bounds.width,bounds.height,[self colorName:fillColor]);
}
-(NSString *)colorName:(ShapColor)color //circle的私有方法(其他對象不能訪問)
{
NSString *colorName = nil;
switch (color) {
case kRedColor:
colorName = @"Red";
break;
case kBlueColor:
colorName = @"Blue";
break;
case kGreenColor:
colorName = @"Green";
break;
default:
break;
}
return colorName;
}
@end
補充:
1.方法前的加減號爲:減號爲實例化對象的方法,加號是類的方法
2.實例是對的對象的另一種說法
3.對象是一種包含值和指向其來得隱藏指針的結構體
4.消息是對象要執行的操作
5.過程式程序建立在函數之上,數據爲函數服務;面向對象的思想是以程序的數據爲中心。函數爲數據服務。在OOP中,不再重點關注程序中的數據,而是專注於數據
(狗爲一個類的話,那麼我家的兜兜(金毛)就是一個對象,會叫就是他的方法,我發送一個消息叫她叫,她就叫了)