从另一个实例方法中创建新的类实例(目标 C)

发布于 2024-12-12 09:33:55 字数 957 浏览 1 评论 0原文

我(本质上)是编程新手,并且正在尝试学习 Objective-C。我正在开发一个单位转换程序,该程序使用类的实例来存储和转换单位。例如,如果我想将 1 英尺转换为英寸,程序将执行以下操作:

  1. 创建 Length 类的新实例 (myLength)
  2. 将值和单位存储在该类的新实例 (myMass) 中
  3. 调用实例方法将值转换为新单位

我的长度类工作正常,正如我所期望的那样。

现在我想创建一个名为 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:

  1. Create a new instance of Length class (myLength)
  2. Store the value and unit in a new instance of the class (myMass)
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞梦里开花 2024-12-19 09:33:55

您需要在 Area.h 中导入 Length 头文件

#import "Length.h"

You need to import your Length header file in Area.h

#import "Length.h"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文