我正在尝试在 Windows 上学习目标 c。我的程序编译时出现警告
我的代码是
#include <objc/Object.h>
@interface Greeter:Object
{
/* This is left empty on purpose:
** Normally instance variables would be declared here,
** but these are not used in our example.
*/
}
- (void)greet;
@end
#include <stdio.h>
@implementation Greeter
- (void)greet
{
printf("Hello, World!\n");
}
@end
#include <stdlib.h>
int main(void)
{
id myGreeter;
myGreeter=[[Greeter alloc] init];
[myGreeter greet];
[myGreeter release];
return EXIT_SUCCESS;
}
我使用以下命令在 GNUStep 上编译我的程序
gcc -o Greeter Greeter.m -I /GNUstep/System/Library/Headers -L /GNUstep/System/Libra
/Libraries -lobjc -lgnustep-base -fconstant-string-class=NSConstantString
我在编译时收到以下警告
: 'Greeter' may not respond to '+alloc' [enabled by default]
: (Messages without a matching method signature [enabled by default]
: will be assumed to return 'id' and accept [enabled by default]
: '...' as arguments.) [enabled by default]
: no '-init' method found [enabled by default]
: no '-release' method found [enabled by default]
因此,当我运行我的可执行文件时,该对象不会被实例化。
我正在使用来自 MinGW 的 gcc,其中 gcc 版本是 4.6.2
- 更新 - -
当我从 NSObject 而不是 Object 扩展时,程序运行良好
--更新 2 ----
我的 Object.h 看起来像
#include <objc/runtime.h>
@interface Object
{
Class isa;
}
@end
--更新 3 ----
我修改了我的代码如下。它编译得很好,但我不确定这是否是正确的处理方式
@interface Greeter
{
/* This is left empty on purpose:
** Normally instance variables would be declared here,
** but these are not used in our example.
*/
}
- (void)greet;
+ (id)alloc;
- (id)init;
- release;
@end
#include <stdio.h>
@implementation Greeter
- (void)greet
{
printf("Hello, World!\n");
}
+ (id)alloc
{
printf("Object created");
return self;
}
- (id)init
{
printf("Object instantiated");
return self;
}
- release {}
@end
#include <stdlib.h>
int main(void)
{
id myGreeter;
myGreeter=[[Greeter alloc] init];
[myGreeter greet];
[myGreeter release];
return EXIT_SUCCESS;
}