设为首页 加入收藏

TOP

Objective-C和C++混编的要点
2014-11-24 07:40:30 来源: 作者: 【 】 浏览:0
Tags:Objective-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
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;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇iOS中常用的四种数据持久化方法 下一篇Objective-C调用C++代码

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何使用 python 中 (2025-12-25 20:49:19)
·零基础如何学爬虫技 (2025-12-25 20:49:17)
·Java 并发工具类:提 (2025-12-25 20:25:44)
·Java面试技巧:如何 (2025-12-25 20:25:41)
·Java并发编程中的线 (2025-12-25 20:25:38)