[問題] obj-c 基本問題

看板MacDev作者 (小犬)時間11年前 (2014/01/24 22:51), 編輯推噓1(1019)
留言20則, 6人參與, 最新討論串1/1
這程式是書本上一題簡單的例題,用物件 方法顯示出a+bi a為實部 b為虛部 有疑問的地方已經註解在程式碼中 (@implementation 區段裏面 print定義之內容) 想請問要如何在方法裡,呼叫方法來給值 code 如下:(因為是前面單元範例,所以檔案未分割) // // main.m // prog1 // // Created by Max on 2014/1/17. // Copyright (c) 2014年 Max. All rights reserved. // #import <Foundation/Foundation.h> @interface Complex: NSObject -(void) setReal: (double) a; -(void) setImaginary: (double) b; -(void) print; // display as a+bi -(double) real; -(double) imaginary; @end @implementation Complex { double real; double imaginary; } -(void) setReal: (double) a { real = a; } -(void) setImaginary: (double) b { imaginary = b; } -(void) print // display as a+bi { NSLog(@"The complex numbers is %f + %fi", real, imaginary); //為何不能用NSLog(@"The complex numbers is %f + %fi", [Complex real],[Complex imaginary]); } -(double) real { return real; } -(double) imaginary { return imaginary; } @end int main(int argc, const char * argv[]) { @autoreleasepool { Complex *Fraction = [Complex new]; [Fraction setReal:2]; [Fraction setImaginary:100]; [Fraction print]; NSLog(@"The complex numbers is %f + %fi", [Fraction real],[Fraction imaginary]); } return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.162.222.132

01/24 23:00, , 1F
self.real, self.imaginary
01/24 23:00, 1F

01/24 23:22, , 2F
感謝!!居然可以了,我查一下self指令的意義
01/24 23:22, 2F

01/24 23:23, , 3F
謝謝,原來在方法中藥呼叫其他方法使用self
01/24 23:23, 3F

01/25 01:48, , 4F
self 代表類別本身,也就是Complex 這個類別自己
01/25 01:48, 4F

01/25 01:54, , 5F
不能用[Complex real]是因為未建立Complex實體,所以
01/25 01:54, 5F

01/25 01:55, , 6F
編譯時會不知道去哪邊找 real 這個 method
01/25 01:55, 6F

01/25 03:26, , 7F
在自己的implemantation底下呼叫自己的method要用self
01/25 03:26, 7F

01/25 03:27, , 8F
[self real] 相等於 self.real
01/25 03:27, 8F

01/25 03:29, , 9F
而這個self就是你在main.m裡創的Complex物件
01/25 03:29, 9F

01/25 03:29, , 10F
不過你的Complex物件為什麼要叫Fraction啊?
01/25 03:29, 10F

01/25 03:35, , 11F
如果你跟我看同本書的話 第7章會解釋這個名詞
01/25 03:35, 11F

01/25 09:44, , 12F
看起來……大家看的都是同一本書了。
01/25 09:44, 12F

01/25 09:45, , 13F
不過我想只要有寫過任何一種語言的物件導向
01/25 09:45, 13F

01/25 09:46, , 14F
這個問題應該很容易理解了。(我剛跳練objective-c無痛學習)
01/25 09:46, 14F

01/25 15:32, , 15F
因為我很懶直接用上個例題改,名稱應該無大礙
01/25 15:32, 15F

01/25 15:32, , 16F
當然我知道真正寫時,名稱其實很重要
01/25 15:32, 16F

01/25 15:33, , 17F
謝謝樓上各位大大解釋!我了解了(:
01/25 15:33, 17F

01/25 23:31, , 18F
請問一下是用哪本書? 小弟之前買的太舊了 謝謝
01/25 23:31, 18F

01/26 00:44, , 19F
Programming in Objective-C / 精通 Objective-C 程式設計
01/26 00:44, 19F

01/26 00:44, , 20F
最近英文版出了六版
01/26 00:44, 20F
文章代碼(AID): #1IudtyMC (MacDev)
文章代碼(AID): #1IudtyMC (MacDev)