一,類的定義
@interface Circle : NSObject //類的定義放在.h文件中
{
ShapeColor fillColor;
ShapeRect bounds; //數據成員
}
//void類型方法,帶有一個ShapeColor類型形參
- (void) setFillColor : (ShapeColor) fillColor;
//void類型方法,帶有一個ShapeRect類型形參和一個int型形參,setBounds:和atindex:
- (void) setBounds : (ShapeRect) bounds
atIndex : (int) index;
//void類型方法,不帶參數.
- (void) draw;
@end //完成聲明
二,類的實現部分(代碼存放於.m文件中[相當於c++中的.cpp文件])
@implementation Circle
- (void) setFillColor : (ShapeColor) c
{ fillColor = c ; }
- (void) setBounds : (ShapeRect) b
atIndex : (int) index;
{ bounds = b ; index++; }
- (void) draw
{ NSLog(@"drawing a circle at (%d,%d,%d,%d) in %@"),
bounds.x , bounds.y , bounds.width , bounds.height,
colorName(fillColor));
}
//colorName是一個返回說明顏色的NSString類型字符串的方法
@end //沒有分號
三,調用帶參方法(使用前文所建類的方法)
① 例:一個帶一個參數的方法( object - c ):
[ circle setFillColor : kRedColor ]
一個帶一個參數的方法(c++):
circle.setFillColor(kRedColor);
② 例:一個帶兩個參數的方法( object - c ):
[ circle setBounds : bound
atIndex : 1];
一個帶兩個參數的方法(c++):
circle.setBounds(bound , 1);
四,new語句
id shape[3] ;
shape[0] = [Circle new] // [ 類 new ]
用c++表示:
Circle (*shape)[3];
shape[0] = new Circle();
五,類的繼承
//Circle類從Shape類繼承所有變量以及方法
@interface Circle : Shape
@end
/**假設Shape類中含有空方法 - (void) draw{} 則可在Circle的實現中對draw方法進行重構 **/
@implementation Circle
- (void) draw
{ NSLog(@"........");}
@end
六,複合 -- 對象間的組合,形成新的類(與繼承比較)
繼承 --- "is a", 具有"是一個"關係 ,"X是一個Y",使用繼承.
複合 --- "has a",具有"有一個"關係,"X有一個Y",使用複合.
七,@class
在.h文件中定義類時使用@class聲明一個未包.h頭文件的類,可使編譯通過,並正常使用.當然要在主程序中把需要的頭文件包括完整.
這個操作相當於告訴編譯器:"相信我,你以後會知道這個類是怎樣的."