看板 MacDev 關於我們 聯絡資訊
這程式是書本上一題簡單的例題,用物件 方法顯示出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
dearlove:self.real, self.imaginary 01/24 23:00
Tall781218:感謝!!居然可以了,我查一下self指令的意義 01/24 23:22
Tall781218:謝謝,原來在方法中藥呼叫其他方法使用self 01/24 23:23
ERTT:self 代表類別本身,也就是Complex 這個類別自己 01/25 01:48
ERTT:不能用[Complex real]是因為未建立Complex實體,所以 01/25 01:54
ERTT:編譯時會不知道去哪邊找 real 這個 method 01/25 01:55
ishuen:在自己的implemantation底下呼叫自己的method要用self 01/25 03:26
ishuen:[self real] 相等於 self.real 01/25 03:27
ishuen:而這個self就是你在main.m裡創的Complex物件 01/25 03:29
ishuen:不過你的Complex物件為什麼要叫Fraction啊? 01/25 03:29
ishuen:如果你跟我看同本書的話 第7章會解釋這個名詞 01/25 03:35
tkdmaf:看起來……大家看的都是同一本書了。 01/25 09:44
tkdmaf:不過我想只要有寫過任何一種語言的物件導向 01/25 09:45
tkdmaf:這個問題應該很容易理解了。(我剛跳練objective-c無痛學習) 01/25 09:46
Tall781218:因為我很懶直接用上個例題改,名稱應該無大礙 01/25 15:32
Tall781218:當然我知道真正寫時,名稱其實很重要 01/25 15:32
Tall781218:謝謝樓上各位大大解釋!我了解了(: 01/25 15:33
donnolove:請問一下是用哪本書? 小弟之前買的太舊了 謝謝 01/25 23:31
ishuen:Programming in Objective-C / 精通 Objective-C 程式設計 01/26 00:44
ishuen:最近英文版出了六版 01/26 00:44