您的位置:首页 > 编程语言 > C语言/C++

第04天OC语言(13):自定义构造方法以及成员变量名称注意点

2017-07-15 00:00 495 查看
不要等到明天,明天太遥远,今天就行动。

#####须读:看完该文章你能做什么?

学习到构造方法的一些注意点

#####学习前:你必须会什么?

什么是自定义构造方法
自定义构造方法:
其实就是自定义一个init方法


#####一、本章笔记

 注意 : 自定义构造方法中的init后面的With的W一定要大写
 注意 : 属性名称不要以new开头,有可能会引发一些未知错误
 注意 : 方法名也不要以new开头

#####二、code
######main.m

#pragma mark 13-自定义构造方法以及成员变量名称注意点
#pragma mark 概念
/*
 注意 : 自定义构造方法中的init后面的With的W一定要大写
 注意 : 属性名称不要以new开头,有可能会引发一些未知错误
 注意 : 方法名也不要以new开头
 */
#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Student.h"
#import "Person.h"
#pragma mark - main函数
int main(int argc, const char * argv[])
{
    //    Student *s = [[Student alloc]initWithAge:33 andName:@"lyh"];
    Student *s = [[Student alloc]initWithAge:33 andName:@"lyh" andNo:1];
    NSLog(@"%@",s);
    
    Person *p = [[Person alloc]init];
//    p->newHeight = 1.71;
    [p newTest];
    NSLog(@"%@",p);
    return 0;
}

######Person

>>>.h
#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    // 注意: 属性名称不要以new开头,有可能会引发一些未知错误
    double newHeight;
}
@property int age;
@property NSString *name;
//@property double newHeight;

- (void)newTest;
- (instancetype)initWithAge:(int)age;
//- (instancetype)initwithAge:(int)age; // 错误写法
- (instancetype)initWithName:(NSString *)name;
- (instancetype)initWithAge:(int)age andName:(NSString *)name;

@end

>>>.m
#import "Person.h"

@implementation Person

- (void)newTest
{
    NSLog(@"---");
}
- (instancetype)init
{
    if (self = [super init]) {
        _age = 10;
    }
    return self;
}

- (instancetype)initWithAge:(int)age
// 注意 : 自定义构造方法中的init后面的With的W一定要大写
//- (instancetype)initwithAge:(int)age
{
    if (self = [super init]) {
        _age = age;
    }
    return self;
}

- (instancetype)initWithName:(NSString *)name
{
    if (self = [super init]) {
        _name = name;
    }
    return self;
}

- (instancetype)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super init]) {
        _age = age;
        _name = name;
    }
    return self;
}

- (NSString *)description
{
    NSLog(@"%f",newHeight);
    return [NSString stringWithFormat:@" age = %i , name = %@",_age,_name];
}

@end

######Student

>>>.h

#import "Person.h"

@interface Student : Person

@property int no; // 学号
- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no;

@end

>>>.m
#import "Student.h"

@implementation Student

- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no
{
    /*
    if (self = [super init]) {
//        _age = age; // 父类的属性不能使用 _去访问
        // 狗拿耗子 多管闲事
        // 自己的事情自己做
        [self setAge:age];
        [self setName:name];
        _no = no;
    }
     */
    
    if (self = [super initWithAge:age andName:name]) {
        _no = no;
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@" age = %i , name = %@ no = %i",[self age],[self name],_no];
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  OC语言
相关文章推荐