嘿所有,我是编程新手,并通过一本客观的书来学习语言和编程基础知识。我反复查看了代码,回到了本书的例子,并试图理解gcc的错误。这是我的代码:
#import <stdio.h>
#import <objc/Object.h>
@interface Point: Object
{
int xaxis;
int yaxis;
}
-(void) print;
-(void) setx: (int)x;
-(void) sety: (int)y;
@end
@implementation Point;
-(void) print
{
printf("(%i,%i)", xaxis, yaxis);
}
-(void) setx: (int) x
{
xaxis = x;
}
-(void) sety: (int) y
{
yaxis = y;
}
@end
int main (int argc, char *argv[])
{
Point *myPoint;
myPoint = [Point alloc];
myPoint = [myPoint init];
[myPoint setx: 4];
[myPoint sety: 5];
printf("The coordinates are: ");
[myPoint print];
printf("\n");
[myPoint free];
return 0;
}
然后gcc的编译错误如下所示:
urban:Desktop alex$ gcc point.m -o point -l objc
point.m: In function ‘main’:
point.m:38: warning: ‘Point’ may not respond to ‘+alloc’
point.m:38: warning: (Messages without a matching method signature
point.m:38: warning: will be assumed to return ‘id’ and accept
point.m:38: warning: ‘...’ as arguments.)
point.m:40: error: ‘mypoint’ undeclared (first use in this function)
point.m:40: error: (Each undeclared identifier is reported only once
point.m:40: error: for each function it appears in.)
point.m:49: warning: ‘Point’ may not respond to ‘-free’
我哪里错了?
顺便说一下,如果你想知道,我会通过Stephen Kochan的“Objective-C编程”。
答案 0 :(得分:2)
首先,基类应该是NSObject,而不是Object
执行初始化的正常方法是在同一语句中编写alloc和init。你通常会有一个 - (id)init;你班上的方法:
-(id)init
{
if ( ( self = [super init] ) )
{
; // additional initialization goes here
}
return self;
}
和
int main (int argc, char *argv[])
{
Point *myPoint = [[Point alloc] init];
更好地使用属性,然后为您自动生成setter和getter
而不是
@interface Point: Object
{
int xaxis;
int yaxis;
}
写
@interface Point : NSObject
{
}
@property int xaxis;
@property int yaxis;
然后当你指定时,你可以写
[myPoint setXaxis:4]
或
myPoint.xaxis = 4;
当您释放对象写入版本时,不是免费的
[myPoint release];
HTH
答案 1 :(得分:0)
您忘记包含标题Foundation.h:
#import <Foundation/Foundation.h>
答案 2 :(得分:0)
您有警告和错误。警告似乎表明,您正在进行子类化的Object
并未实现alloc
,init
或free
。通常情况下,在Apple平台上,你确实是NSObject
的子类,它实现了这些,但不知道你在哪个平台上,就不可能建议正确的选项。< / p>
其次,你有一个错字,但现在似乎已经纠正了。此
point.m:40: error: ‘mypoint’ undeclared (first use in this function)
建议您在代码中使用mypoint
,而不是myPoint
。