[学习笔记—Objective-C]《Objective-C 程序设计 第6版》第七章 类 课后题 7-6 解析

时间:2022-12-26 09:44:56

题目:
根据第四章的课后题4-6,添加一个新的方法add:,用来求两个复数之和。代码为本人原创。

代码:

  • 声明文件:
#import <Foundation/Foundation.h>

@interface Complex : NSObject

@property double real, imaginary;

-(void) setReal: (double) a andsetImaginary: (double) b;
-(Complex *) add: (Complex *) complexNum;//两个复数的加法

-(void) print;

@end
  • 实现文件:

#import "Complex.h"


@implementation Complex

@synthesize real, imaginary;

-(void) setReal: (double) a andsetImaginary: (double) b
{
real = a;
imaginary = b;
}

-(Complex *) add: (Complex *) complexNum
{
Complex *result = [[Complex alloc] init]; //存储结果的新对象

result.real = real + complexNum.real;
result.imaginary = imaginary + complexNum.imaginary;

return result;
}

-(void) print;
{
NSLog(@"Tht complex number is %g + %gi", real, imaginary);
}


@end
  • 主文件:

#import <Foundation/Foundation.h>
#import "Complex.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {

Complex *myComplex1 = [[Complex alloc] init];
Complex *myComplex2 = [[Complex alloc] init];

Complex *complexResult; //存储结果

//为两个复数赋值
[myComplex1 setReal:5.3 andsetImaginary:7];
[myComplex2 setReal:2.7 andsetImaginary:4];

complexResult = [myComplex1 add:myComplex2];

[complexResult print];
}
return 0;
}