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;
}