今天的topic是如何使用objective c 与 c++ 进行混合编程
参考的代码是苹果官方的文档,地址如下:
1。首先创建一个新的project,使用的模板是"Mac os x" -> "Application" -> " Command line tool(Foundation)",命名为Hello。
2。在xcode左侧可以看见文件列表,在"Group&Files"下面可以找到Hello.m文件,将其重命名为Hello.mm,以启动objecitvec++编译器。
3。在Hello.mm文件中,键入如下代码:
/* 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 { |
self = [super init]; |
if (self) { |
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; |
} |
4。Build And Run。
至此第一个混编的程序已经完成,在摸索的过程中,我遇到了如下的问题:
1。不知道该创建一个以什么为模板的项目?
2。不知道该将c++代码写在哪里?
3。不知道怎样启动objective c++编译器(即,怎样创建一个mm文件)
3。不知道c++和objectivec代码之间的关系。