這程式是書本上一題簡單的例題,用物件 方法顯示出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;
}