Objective-C和C++混编的要点


Using C++ With Objective-C

苹果的Objective-C编译器允许用户在同一个源文件里自由地混合使用C++和Objective-C,混编后的语言叫Objective-C++。有了它,你就可以在Objective-C应用程序中使用已有的C++类库。

Objective-C和C++混编的要点

在 Objective-C++中,可以用C++代码调用方法也可以从Objective-C调用方法。在这两种语言里对象都是指针,可以在任何地方使用。例 如,C++类可以使用Objective-C对象的指针作为数据成员,Objective-C类也可以有C++对象指针做实例变量。下例说明了这一点。

注意:Xcode需要源文件以".mm"为扩展名,这样才能启动编译器的Objective-C++扩展。

/* Hello.mm
 * Compile with: g++ -x objective-c++ -framework Foundation Hello.mm  -o hello
 */
#import <Foundation/Foundation.h>
class Hello {
private:
    id greeting_text;  // holds an NSString
public:
    Hello() {
        greeting_text = @"Hello, world!";
    }
    Hello(const char* initial_greeting_text) {
        greeting_text = [[NSString alloc] initWithUTF8String:initial_greeting_text];
    }
    void say_hello() {
        printf("%s/n", [greeting_text UTF8String]);
    }
};
@interface Greeting : NSObject {
@private
    Hello *hello;
}
- (id)init;
- (void)dealloc;
- (void)sayGreeting;
- (void)sayGreeting:(Hello*)greeting;
@end
@implementation Greeting
- (id)init {
    if (self = [super init]) {
        hello = new Hello();
    }
    return self;
}
- (void)dealloc {
    delete hello;
    [super dealloc];
}
- (void)sayGreeting {
    hello->say_hello();
}
- (void)sayGreeting:(Hello*)greeting {
    greeting->say_hello();
}
@end
int main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
    Greeting *greeting = [[Greeting alloc] init];
    [greeting sayGreeting];                        // > Hello,  world!
   
    Hello *hello = new Hello("Bonjour, monde!");
    [greeting sayGreeting:hello];                  // > Bonjour,  monde!
   
    delete hello;
    [greeting release];
    [pool release];
    return 0;
}

  • 1
  • 2
  • 3
  • 下一页

相关内容