从另一个实例方法中创建新的类实例(目标 C)
我(本质上)是编程新手,并且正在尝试学习 Objective-C。我正在开发一个单位转换程序,该程序使用类的实例来存储和转换单位。例如,如果我想将 1 英尺转换为英寸,程序将执行以下操作:
- 创建 Length 类的新实例 (myLength)
- 将值和单位存储在该类的新实例 (myMass) 中
- 调用实例方法将值转换为新单位
我的长度类工作正常,正如我所期望的那样。
现在我想创建一个名为 Area 的新类,它创建 Length 类的两个实例,并使用 Length 类来执行转换。但是,当我尝试从 Area.m 中声明 Length 类的新实例时,我收到警告“长度未声明”。
是否可以在实例方法中创建不同类的实例?更具体地说,我可以从 Area 类实例方法中创建 Length 类的两个实例吗?
(如果我用错了任何术语,请提前原谅我)。
这是 Area.m 中给我带来麻烦的代码片段:
@implementation Area
-(void) setCompound: (double) myVal unit1: (char) c1 unit2: (char) c2
{
// Create two new instances of the Length class
// THE FOLLOWING TWO LINES ARE GIVING ME TROUBLE
Length * aLength = [[Length alloc] init];
Length * bLength = [[Length alloc] init];
[aLength setLength:myVal units: c1]; // Set the value and units of first length
[bLength setLength: 1 units: c2]; // Set the value and units of the second length
}
@end
I am (essentially) new to programming and attempting to learn Objective-C. I am working on a unit conversion program that uses an instance of a class to store and convert a unit. So for example, if I would like to convert 1 ft to inches, the program does the following:
- Create a new instance of Length class (myLength)
- Store the value and unit in a new instance of the class (myMass)
- Call an instance method to convert the value to new units
My Length class is working fine and just as I expect.
Now I would like to create a new class called Area that creates two instances of the Length class, and uses the Length class to perform the conversions. However, when I attempt to declare a new instance of my Length class from within Area.m, I get the warning "Length undeclared".
Is it possible to create an instance of a different class from within an instance method? More specifically, can I create two instances of my Length class from within the Area class instance method?
(Please forgive me in advance if I have botched any of my terminology).
Here's a snippet of the code in Area.m that is giving me trouble:
@implementation Area
-(void) setCompound: (double) myVal unit1: (char) c1 unit2: (char) c2
{
// Create two new instances of the Length class
// THE FOLLOWING TWO LINES ARE GIVING ME TROUBLE
Length * aLength = [[Length alloc] init];
Length * bLength = [[Length alloc] init];
[aLength setLength:myVal units: c1]; // Set the value and units of first length
[bLength setLength: 1 units: c2]; // Set the value and units of the second length
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在 Area.h 中导入 Length 头文件
You need to import your Length header file in Area.h