作者Tall781218 (小犬)
看板MacDev
标题[问题] obj-c 基本问题
时间Fri Jan 24 22:51:35 2014
这程式是书本上一题简单的例题,用物件 方法显示出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
1F:→ dearlove:self.real, self.imaginary 01/24 23:00
2F:→ Tall781218:感谢!!居然可以了,我查一下self指令的意义 01/24 23:22
3F:→ Tall781218:谢谢,原来在方法中药呼叫其他方法使用self 01/24 23:23
4F:→ ERTT:self 代表类别本身,也就是Complex 这个类别自己 01/25 01:48
5F:→ ERTT:不能用[Complex real]是因为未建立Complex实体,所以 01/25 01:54
6F:→ ERTT:编译时会不知道去哪边找 real 这个 method 01/25 01:55
7F:→ ishuen:在自己的implemantation底下呼叫自己的method要用self 01/25 03:26
8F:→ ishuen:[self real] 相等於 self.real 01/25 03:27
9F:→ ishuen:而这个self就是你在main.m里创的Complex物件 01/25 03:29
10F:→ ishuen:不过你的Complex物件为什麽要叫Fraction啊? 01/25 03:29
11F:→ ishuen:如果你跟我看同本书的话 第7章会解释这个名词 01/25 03:35
12F:→ tkdmaf:看起来……大家看的都是同一本书了。 01/25 09:44
13F:→ tkdmaf:不过我想只要有写过任何一种语言的物件导向 01/25 09:45
14F:→ tkdmaf:这个问题应该很容易理解了。(我刚跳练objective-c无痛学习) 01/25 09:46
15F:→ Tall781218:因为我很懒直接用上个例题改,名称应该无大碍 01/25 15:32
16F:→ Tall781218:当然我知道真正写时,名称其实很重要 01/25 15:32
17F:→ Tall781218:谢谢楼上各位大大解释!我了解了(: 01/25 15:33
18F:推 donnolove:请问一下是用哪本书? 小弟之前买的太旧了 谢谢 01/25 23:31
19F:→ ishuen:Programming in Objective-C / 精通 Objective-C 程式设计 01/26 00:44
20F:→ ishuen:最近英文版出了六版 01/26 00:44