混合Objective-C和C ++ [英] Mixing Objective-C and C++

查看:129
本文介绍了混合Objective-C和C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图混合Objective-C和C ++。当我编译代码时,会出现几个错误。

I'm trying to mix Objective-C with C++. When I compile the code, I get several errors.

Ah

#import <Cocoa/Cocoa.h>
#include "B.h"

@interface A : NSView {
    B *b;
}

-(void) setB: (B *) theB;

@end

Am

#import "A.h"

@implementation A

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
}

-(void) setB: (B *) theB {
    b = theB;
}

@end

Bh

#include <iostream>

class B {

    B() {
        std::cout << "Hello from C++";
    }

};

以下是错误:

/Users/helixed/Desktop/Example/B.h:1:0 /Users/helixed/Desktop/Example/B.h:1:20: error: iostream: No such file or directory
/Users/helixed/Desktop/Example/B.h:3:0 /Users/helixed/Desktop/Example/B.h:3: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'B'
/Users/helixed/Desktop/Example/A.h:5:0 /Users/helixed/Desktop/Example/A.h:5: error: expected specifier-qualifier-list before 'B'
/Users/helixed/Desktop/Example/A.h:8:0 /Users/helixed/Desktop/Example/A.h:8: error: expected ')' before 'B'
/Users/helixed/Desktop/Example/A.m:26:0 /Users/helixed/Desktop/Example/A.m:26: error: expected ')' before 'B'
/Users/helixed/Desktop/Example/A.m:27:0 /Users/helixed/Desktop/Example/A.m:27: error: 'b' undeclared (first use in this function)


推荐答案

您需要为 .m 文件命名 .mm 。你可以使用Objective-C编译C ++代码。

You need to name your .m files .mm. And you will be able to compile C++ code with Objective-C.

因此,按照你的例子,你的 AView.m AView.mm 。这很简单。它工作得很好。我使用了很多std容器(std :: vector,std :: queue等)和遗留的C ++代码在iPhone项目没有任何复杂性。

So, following your example, your AView.m file should be named AView.mm. It's simple as that. It works very well. I use a lot of std containers (std::vector, std::queue, etc) and legacy C++ code in iPhone projects without any complications.

这篇关于混合Objective-C和C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆