黑马程序员技术交流社区
标题:
日课21 OC的类与对象
[打印本页]
作者:
黑白世界
时间:
2015-10-8 23:07
标题:
日课21 OC的类与对象
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;
}
复制代码
作者:
Brisingr
时间:
2015-10-9 20:42
学习了虽然我还没学到这里
作者:
木亙。
时间:
2015-10-9 21:24
看不太懂~~
作者:
wxd123
时间:
2015-10-9 21:40
看得似懂非懂的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2