1.类的声明
@interface 类名:父类名
{ 属性声明}
方法声明
@end
2.类的实现
@implementation
方法的实现
@end
3.创建对象,调用属性,调用方法(举例:类名Car 属性color 方法run)
Car *c1 = [Car new];
c1->color;
[car run];
4.有两个参数的方法的声明、实现和调用
声明:
-(返回值类型)方法名1:(参数类型1)参数1 方法名2:(参数类型2)参数2;
实现:
-(返回值类型)方法名1:(参数类型1)参数1 方法名2:(参数类型2)参数2{ }
调用:
[对象名 方法名1:参数1 方法名2:参数2];
代码举例:有一个类,类名是Student,它有三个属性:age,name,sex。有两个方法:sayHello和suanJiaFa.
- #import <Foundation/Foundation.h>
- //类的声明
- @interface Student : NSObject
- { @public;
- int age;
- NSString *name;
- NSString *sex;
- }
- -(void) sayHello;
- -(int) suanJiaFa:(int) num1 and:(int) num2;
- @end
- //类的实现
- @implementation Student
- -(void) sayHello{
- NSLog(@"Hello EveryOne!");
- }
- -(int) suanJiaFa:(int) num1 and:(int) num2{
- return num1 + num2;
- }
- @end
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // 实现Student类的实例stuXiaoMing
- Student *stuXiaoMing = [Student new];
- //为属性赋值
- stuXiaoMing->age = 22;
- stuXiaoMing->name = @"小明";
- stuXiaoMing->sex = @"男";
-
- //调用无返回值的方法
- [stuXiaoMing sayHello];
- //调用属性
- NSLog(@"我叫 %@",stuXiaoMing->name);
- NSLog(@"性别 %@,年龄 %d岁!",stuXiaoMing->sex,stuXiaoMing->age);
- //调用有返回值有参数的方法
- int s = [stuXiaoMing suanJiaFa:22 and:23];
- NSLog(@"我会算加法,22+23=%d",s);
-
- }
- return 0;
- }
复制代码
|
|