我有一些Objective-C ++代码,我试图从Objective-C对象中获取事件来调用C ++对象中的方法。我对Objective-C很新,所以我可能做错了。
示例:
@interface KnobClass {
}
-(void)Event;
@end
class DoorClass {
public:
KnobClass * knob;
void start() { knob = [[KnobClass allocate] init]; }
};
class AlarmClass {
public:
void Alert();
};
class HouseClass {
public:
DoorClass door;
AlarmClass alarm;
};
int main() {
//...
HouseClass house;
house.door.start();
//...
return 0;
}
方法[house.door.knob Event]
是针对某个事件生成的,我希望它能够调用house.alarm.Alert()
。但我很困惑如何以正确的方式实现这一目标。有人可以提出一种方法来实现这个目标吗?
答案 0 :(得分:2)
我也在学习Objective-C。这适用于gcc 4.3.3:
#import <Foundation/Foundation.h>
class AlarmClass {
public:
void Alert() {
printf("Alert!\n");
}
};
@interface KnobClass: NSObject {
AlarmClass *alarm;
}
-(void)Event;
-(id)initWithAlarm:(AlarmClass*) alarm;
@end
@implementation KnobClass: NSObject
-(id)initWithAlarm:(AlarmClass*) a
{
self = [super init];
alarm = a;
return self;
}
-(void)Event
{
alarm->Alert();
}
@end
class DoorClass {
public:
KnobClass * knob;
void start(AlarmClass *a) {
knob = [[KnobClass alloc] initWithAlarm: a];
}
void doEvent() {
[knob Event];
}
};
class HouseClass {
public:
DoorClass door;
AlarmClass alarm;
};
int main(int argc, const char *argv[]) {
//...
HouseClass house;
house.door.start(&house.alarm);
house.door.doEvent();
//...
return 0;
}