Objective-C 面向对象基础-构造方法
2014-11-09 13:47
567 查看
OC中的类使用的是两段的构造方法,这与通常的C++和Java不同,如果想通过构造的方式传递参数,可以重载一个init方法,下面贴代码。
// // Goods.h // 04_Description // // Created by apple on 14-11-9. // Copyright (c) 2014年 cc. All rights reserved. // #import <Foundation/Foundation.h> @interface Goods : NSObject { int _price; int _count; } /** * 多参的构造方法 * * @param price 价格 * @param count 数量 * * @return 当前类的对象 */ - (id)initWithAttribute:(int)price:(int)count; - (void)setPrice:(int)price; - (int)price; - (void)setCount:(int)count; - (int)count; @end
// // Goods.m // 04_Description // // Created by apple on 14-11-9. // Copyright (c) 2014年 cc. All rights reserved. // #import "Goods.h" @implementation Goods /** * 多参的构造方法 * * @param price 价格 * @param count 数量 * * @return 当前类的对象 */ -(id)initWithAttribute:(int)price :(int)count { //需要调用父类(super)的构造来初始化当前类的对象 self = [super init]; if (self) { //给成员属性赋值 _price = price; _count = count; } // id类型可以代表任意类型的对象,这里是返回当前类的对象 return self; } -(void)setPrice:(int)price { _price = price; } -(int)price { return _price; } -(void)setCount:(int)count { _count = count; } -(int)count { return _count; } @end
// // main.m // 04_Description // // Created by apple on 14-11-9. // Copyright (c) 2014年 cc. All rights reserved. // #import <Foundation/Foundation.h> #import "Goods.h" int main(int argc, const char * argv[]) { @autoreleasepool { //通过构造给成员属性赋值赋值 Goods* pGoods = [[Goods alloc] initWithAttribute:10 :20]; NSLog(@"价格=%d, 数量=%d", pGoods.price, pGoods.count); } return 0; }通过控制台输出可以看到通过构造穿参也可以给成员属性赋值。
相关文章推荐
- 面向对象基础续2(static关键字、理解main方法、代码块、构造方法私有化(单例模式)) .
- 黑马程序员---java基础---面向对象中的构造方法及static关键字,变量的问题
- 附录A培训实习生-面向对象基础构造方法和带参数的构造方法(2)
- Java面向对象基础--构造方法
- 面向对象基础知识(2)- 构造方法
- php面向对象基础概念(构造方法和析构方法)
- java 面向对象基础 UML图 构造方法 对象 参数传值 关联关系 依赖关系
- OC基础语法<1.2> 入门面向对象语法-构造方法和description
- JAVA基础初探(三)面向对象思想、类与对象、成员变量与局部变量、构造方法、static关键字详解
- 跟着姜少学Java基础编程之十二:面向对象-构造方法
- JAVA基础再回首(四)——面向对象思想、类与对象、成员/局部变量、匿名对象、封装、private、this、构造方法
- 面向对象基础(类与对象的定义、进一步研究、封装性、构造方法与匿名对象)
- 面向对象基础 之-定义类,声明,属性,成员方法,传值,构造与析构方法
- 黑马程序员--.NET笔记--面向对象基础、构造方法
- Java面向对象基础--构造方法私有化
- Objective-C(五、@class,id类型,类对象构造方法,加载和初始化,description,Logging宏)——iOS开发基础
- Java面向对象基础--类的设计及分析问题的方法---用户登录例子
- java面向对象--this关键字、引用变量、构造方法
- Java面向对象基础--String类中常用的方法
- Java面向对象基础--理解main方法