在XCODE中想使用C++代码,你需要把文件的扩展名从.m改成.mm,这样才会启动g++编译器。
我们来看个测试代码:
- class TestC {
- private:
- NSString *str_;//C++类可以使用OC对象作为成员变量
- public:
- TestC() {
- str_ = @"hi mc0066.";//构造函数内可以使用OC对象来赋值
- }
- TestC(NSString *str) {//函数可以接收OC对象(通过函数参数)
- str_ = str;
- }
- TestC(NSInteger num) {
- str_ = [NSString stringWithFormat:@"%d",num];//C++函数可以调用OC方法
- }
- void show() {
- printf("%s\n",[str_ UTF8String]);
- NSLog(@"str_ is:%@\n",str_);
- }
- };
1. C++函数内可以调用OC方法、可以创建OC对象、函数参数可以为OC对象。
2. C++类的成员变量可以是OC对象。
其实,在混编时,OC和C++的对象都是单纯的指针,所以可以任意的彼此调用对方的方法、使用对方的内部数据。
再来看看OC中是如何使用C++代码的:
- @interface TestOC : NSObject
- {
- TestC *c;//可以使用C++对象作为参数
- }
- - (id)initTestOC;
- - (void)testC;
- @end
- @implementation TestOC
- - (id)initTestOC{
- if ((self = [super init])) {
- c = new TestC();//以C++语法调用构造函数
- }
- return self;
- }
- - (void)testC{
- c->show();//调用C++类的内部函数
- }
- - (void)dealloc{
- delete c;//用完 记得删除C++对象,避免内存泄露
- [super dealloc];
- }
- @end
还有一点要注意,OC类无法继承C++类,C++也一样。因为oc类的结构和c++类结构不同,所以才导致该问题。
提供一个示例:
-
有时候,出于性能或可移植性的考虑,需要在iOS项目中使用到C++。
假设我们用C++写了下面的People类:
[cpp]
//
// People.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#ifndef __MixedWithCppDemo__People__
#define __MixedWithCppDemo__People__
#include <iostream>
class People
{
public:
void say(const char *words);
};
#endif /* defined(__MixedWithCppDemo__People__) */[cpp] view plaincopy
//
// People.cpp
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#include "People.h"
void People::say(const char *words)
{
std::cout << words << std::endl;
}然后,我们用Objective-C封装一下,这时候文件后缀需要为.mm,以告诉编译器这是和C++混编的代码:
[cpp]
//
// PeopleWrapper.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "People.h"
@interface PeopleWrapper : NSObject
{
People *people;
}
- (void)say:(NSString *)words;
@end[cpp] view plaincopy
//
// PeopleWrapper.mm
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#import "PeopleWrapper.h"
@implementation PeopleWrapper
- (void)say:(NSString *)words
{
people->say([words UTF8String]);
}
@end最后,我们需要在ViewController.m文件中使用PeopleWrapper:
[cpp]
PeopleWrapper *people = [[PeopleWrapper alloc] init];
[people say:@"Hello, Cpp.\n"];
[people release], people = nil;结果发现编译通不过,提示“iostream file not found”之类的错误。
这是由于ViewController.m实际上也用到了C++代码,同样需要改后缀名为.mm。修改后缀名后编译通过,可以看到输出“
Hello, Cpp.
”。