标签:
#import <Foundation/Foundation.h> // 类的声明 @interface Car : NSObject { @public int wheels; // 多少个轮子 int speed; // 时速 } - (void)run; // 跑的行为 @end
@public可以让Car对象的wheels和speed属性被外界访问
加上:NSObject的目的是让Car类具备创建对象的能力
// 类的实现 @implementation Car - (void) run { NSLog(@"%i个轮子,%i时速的车子跑起来了", wheels, speed); } @end
// 主函数 int main() { // 创建车子对象 Car *c = [Car new]; c->wheels = 3; c->speed = 300; [c run]; return 0; }
Car *c = [Car new];
用一个指针变量c指向内存中的Car对象
跟用指向结构体的指针访问结构体属性一样,用->
c->wheels = 3; c->speed = 300;
Car *c1 = [Car new]; c1->wheels = 4; Car *c2 = [Car new]; c2->speed = 250; [c1 run];
Car *c1 = [Car new]; c1->wheels = 4; c1->speed = 250; Car *c2 = c1; c2->wheels = 3; [c1 run];
@implementation Car : NSObject { @public int wheels; // 多少个轮子 int speed; // 时速 } - (void) run { NSLog(@"%i个轮子,%i时速的车子跑起来了", wheels, speed); } @end
设计一个Caculator计算器类,它拥有计算的功能(行为)
// 方法声明 - (double)pi; // 方法实现 - (double)pi { return 3.14; }
// 方法声明 - (double)square:(double)number; // 方法实现 - (double)square:(double)number { return number * number; }
// 方法声明 - (double)sumOfNum1:(double)num1 andNum2:(double)num2; // 方法实现 - (double)sumOfNum1:(double)num1 andNum2:(double)num2 { return num1 + num2; }
给Car类设计一个方法,用来和其他车比较车速,如果本车速度快,就返回1,如果本车速度慢,就返回-1,速度相同就返回0
[Car new]->speed = 200;
[ [Car new] run];
标签:
原文地址:http://www.cnblogs.com/chenziqiang/p/4930329.html