这程式是书本上一题简单的例题,用物件 方法显示出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;
}
self.real, self.imaginary
感谢!!居然可以了,我查一下self指令的意义谢谢,原来在方法中药呼叫其他方法使用self
作者: ERTT 2014-01-25 01:48:00
self 代表类别本身,也就是Complex 这个类别自己不能用[Complex real]是因为未建立Complex实体,所以编译时会不知道去哪边找 real 这个 method
作者:
ishuen (小小宇)
2014-01-25 03:26:00在自己的implemantation底下呼叫自己的method要用self[self real] 相等于 self.real而这个self就是你在main.m里创的Complex物件不过你的Complex物件为什么要叫Fraction啊?如果你跟我看同本书的话 第7章会解释这个名词
作者:
tkdmaf (皮皮快跑)
2014-01-25 09:44:00看起来……大家看的都是同一本书了。不过我想只要有写过任何一种语言的物件导向这个问题应该很容易理解了。(我刚跳练objective-c无痛学习)
因为我很懒直接用上个例题改,名称应该无大碍当然我知道真正写时,名称其实很重要谢谢楼上各位大大解释!我了解了(:
作者:
ishuen (小小宇)
2014-01-26 00:44:00Programming in Objective-C / 精通 Objective-C 程式设计最近英文版出了六版