• IOS-day02_OC中类的声明


    在上一个笔记中类的使用中,在编译链接的时候会有警告,原因就是我们没有对类进行声明

    类的声明如下:使用关键字@interface

     1 #import <Foundation/Foundation.h>
     2 
     3 // 声明一个类
     4 
     5 @interface Book : NSObject
     6 {
     7     @public
     8     double price;
     9 }
    10 // 声明一个方法(行为)
    11 -(void) reng;
    12 
    13 @end
    14 
    15 int main(){
    16     Book *b = [Book new];
    17     b->price = 10;
    18     [b reng];
    19     return 0;
    20 }
    21 
    22 // 定义一个类
    23 /*
    24  只用来实现@interface中声明的方法
    25  */
    26 @implementation Book
    27 
    28 -(void)reng{
    29     NSLog(@"书的价格%f",price);
    30 }
    31 
    32 @end

    上述代码中方法的实现中不会有属性,属性只需要在声明的时候定义即可

    OC中声明有参数的方法:

    一个参数:

    1 -(double) cheng:(double)n1;
    2 
    3 //实现
    4 -(double) cheng :(double)n1{
    5     return n1;
    6 }

    对个参数:

    1 -(double) cheng:(double)n1 :(double)n2;
    2 
    3 //实现
    4 -(double) cheng :(double)n1 :(double)n2{
    5     return n1 * n2;
    6 }

    调用带参数的方法:

    1.首先创建对象:Calc *c = [Calc new];

    2.调用:double d = [c cheng:2];   double d2 = [c cheng:2 :3];

    3.为了我们在调用的时候能够知道哪个值是给哪个参数的我们可以再声明的时候这样写:

    1 -(double)num1: (double)n1 andNum2:(double)n2;
    2 
    3 //实现
    4 -(double)num1:(double)n1 andNum2:(double)n2{
    5     return n1 * n2;
    6 }
    7 
    8 //调用
    9 NSLog(@"两数乘积为=%f",[c num1:3 andNum2:4]);

    我们这是给调用num1:方法,传递了两个值,这样可读性更高

  • 相关阅读:
    改变标题栏颜色和顶部栏颜色
    listview崩溃问题
    android欢迎界面
    ASZ参考代码
    shape的使用
    listview加边框
    toolbar左边有一小段空白
    as用百度地图不联网就gg
    OOM-OutOfMemory
    java reference定位
  • 原文地址:https://www.cnblogs.com/liyajie/p/4445549.html
Copyright © 2020-2023  润新知