现在的位置: 首页 > 综合 > 正文

oc 与 c++混编

2013年10月12日 ⁄ 综合 ⁄ 共 1289字 ⁄ 字号 评论关闭

步骤:

1.c++

//  People.h
#ifndef __MXCPPTest__People__
#define __MXCPPTest__People__

#include <iostream>
class People
{
public:
    void say(const char * words);
};
#endif

-----------------

//
//  People.cpp
//  MXCPPTest
//
//  Created by fengshaobo on 12-11-27.
//  Copyright (c) 2012年 fengshaobo. All rights reserved.
//

#include "People.h"
void People::say(const char *words)
{
    std::cout << words << std::endl;
}

2.oc封装

//
//  Student.h
//  MXCPPTest
//
//  Created by fengshaobo on 12-11-27.
//  Copyright (c) 2012年 fengshaobo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "People.h"

@interface Student : NSObject
{
    People *p;
}

- (void)say:(NSString *)words;

@end

-----------------

//
//  Student.mm
//  MXCPPTest
//
//  Created by fengshaobo on 12-11-27.
//  Copyright (c) 2012年 fengshaobo. All rights reserved.
//

#import "Student.h"

@implementation Student
- (void)say:(NSString *)words
{
    p->say([words UTF8String]);
}
@end

3.将.m -> .mm

//
//  ViewController.mm
//  MXCPPTest
//
//  Created by fengshaobo on 12-11-27.
//  Copyright (c) 2012年 fengshaobo. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    Student *s = [[Student alloc] init];
    [s say:@"hello world!"];
    [s release];
    s = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

代码参见:http://download.csdn.net/detail/worn_nest/4817705

抱歉!评论已关闭.