黑马程序员技术交流社区

标题: 日课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.
  1. #import <Foundation/Foundation.h>

  2. //类的声明
  3. @interface Student : NSObject
  4. {   @public;
  5.     int age;
  6.     NSString *name;
  7.     NSString *sex;
  8. }
  9. -(void) sayHello;
  10. -(int) suanJiaFa:(int) num1 and:(int) num2;
  11. @end

  12. //类的实现
  13. @implementation Student
  14. -(void) sayHello{
  15.     NSLog(@"Hello EveryOne!");
  16. }
  17. -(int) suanJiaFa:(int) num1 and:(int) num2{
  18.     return num1 + num2;
  19. }
  20. @end


  21. int main(int argc, const char * argv[]) {
  22.     @autoreleasepool {
  23.         // 实现Student类的实例stuXiaoMing
  24.         Student *stuXiaoMing = [Student new];
  25.         //为属性赋值
  26.         stuXiaoMing->age = 22;
  27.         stuXiaoMing->name = @"小明";
  28.         stuXiaoMing->sex = @"男";
  29.         
  30.         //调用无返回值的方法
  31.         [stuXiaoMing sayHello];
  32.         //调用属性
  33.         NSLog(@"我叫 %@",stuXiaoMing->name);
  34.         NSLog(@"性别 %@,年龄 %d岁!",stuXiaoMing->sex,stuXiaoMing->age);
  35.         //调用有返回值有参数的方法
  36.         int s = [stuXiaoMing suanJiaFa:22 and:23];
  37.         NSLog(@"我会算加法,22+23=%d",s);
  38.         
  39.     }
  40.     return 0;
  41. }

复制代码




作者: Brisingr    时间: 2015-10-9 20:42
学习了虽然我还没学到这里

作者: 木亙。    时间: 2015-10-9 21:24
看不太懂~~
作者: wxd123    时间: 2015-10-9 21:40
看得似懂非懂的




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2