类与类之间调用Computer-CPU-Mouse--看懂它看懂类之间的调用
举个例子
大家会使用类并且会声明并且实现类的setter 和 getter方法
那让我们来更深入的学习,类中包含另一个类的实现方法吧。
题目:
Computer类(电脑类)
该类用于描述一个具体的电脑类,可以对该类进行一些基本的操作
属性:
1. 电脑品牌
2. 鼠标
3.CPU
方法:
1、成员变量的set、get方法
2、电脑信息的详细描述 包括电脑品牌 鼠标信息,CPU信息等等
鼠标类:
鼠标品牌
类别
价格
CPU类:
CPU型号
缓存
价格
解题思路:(有很多种,但大单位为程序员交流方便都做了一些规定,我们还是随大流,让大家养成一个良好的书写习惯。)
定义三个类,因为并没有完全一样的属性可以抽取而只是包含的关系
电脑有cpu和鼠标,但cpu和鼠标不是电脑,所以电脑应该是包含cpu和鼠标,而不是继承。
在电脑属性中包含cpu属性和鼠标属性即可(当然还可以后其他属性,只是举例说明,其他的就不列举了)
在三个类中分别实现它的getter和setter
在电脑类中实现输出电脑详细信息的方法(- (void)showAllDetail;)
以下是实现和main函数,声明略去
#import<Foundation/Foundation.h>
#import"Mouse.h"
#import"CpuType.h"
// Computer类(电脑类)
// 该类用于描述一个具体的电脑类,可以对该类进行一些基本的操作
// 属性:
// 1.电脑品牌
// 2.鼠标
// 3. CPU
@interfaceComputer :NSObject
{
char* _brand;
Mouse* _mouse;
CpuType*_cpu;
}
// setmethod
- (void)setBrand:(char*)brand;
- (void)setMouse:(Mouse*)mouse;
- (void)setCpuType:(CpuType*)cpu;
// get method
- (char*)brand;
- (Mouse*)mouse;
- (CpuType*)cpu;
//电脑信息的详细描述包括电脑品牌鼠标信息,CPU信息等等
// opration method
- (void)showAllDitatil;
@end
#import"Mouse.h"
@implementationMouse
// set method
- (void)setBrand:(char*)brand{
_brand= brand;
}
- (void)setType:(char*)type{
_type= type;
}
- (void)setPrice:(float)price{
_price= price;
}
// get method
- (char*)brand{
return_brand;
}
- (char*)type{
return_type;
}
- (float)price{
return_price;
}
@end
#import"CpuType.h"
@implementationCpuType
// set method
- (void)setType:(char*)type{
_type= type;
}
- (void)setCache:(int)cache{
_cache= cache;
}
- (void)setPrice:(float)price{
_price= price;
}
// get method
- (char*)type{
return_type;
}
- (int)cache{
return_cache;
}
- (float)price{
return_price;
}
@end
#import<Foundation/Foundation.h>
#import"Computer.h"
intmain(intargc,constchar* argv[]) {
@autoreleasepool{
// 练习2
// Computer类(电脑类)
// 该类用于描述一个具体的电脑类,可以对该类进行一些基本的操作
// 属性:
// 1.电脑品牌
// 2.鼠标
// 3. CPU
//
// 方法:
// 1、成员变量的set、get方法
// 2、电脑信息的详细描述包括电脑品牌鼠标信息,CPU信息等等
//
// 鼠标类:
// 鼠标品牌
// 类别
// 价格
// CPU类:
// CPU型号
// 缓存
// 价格
// 1.定义电脑对象
Computer*computer = [[Computeralloc]init];
char*comBrand ="lenovo";
[computersetBrand:comBrand];
// 2.定义鼠标
Mouse* mouse = [[Mousealloc]init];
char* mouseBrand ="jack";
char* mouseType ="hit";
floatmousePrice =1000;
[mousesetBrand:mouseBrand];
[mousesetType:mouseType];
[mousesetPrice:mousePrice];
[computersetMouse:mouse];
// 3.定义CPU
CpuType*cpu = [[CpuTypealloc]init];
char*cpuType ="UFO";
intcpuCache =199;
floatcpuPrice =788.00;
[cpusetType:cpuType];
[cpusetCache:cpuCache];
[cpusetPrice:cpuPrice];
[computersetCpuType:cpu];
// 4.打印信息
[computershowAllDitatil];
}
return0;
}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。