gpt4 book ai didi

c++ - 混合 Objective-C 和 C++

转载 作者:行者123 更新时间:2023-11-30 17:54:05 25 4
gpt4 key购买 nike

我正在尝试将 Objective-C 与 C++ 混合在一起。当我编译代码时,出现几个错误。

啊啊

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

@interface A : NSView {
B *b;
}

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

@end

上午

#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

B.h

#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++ 代码。

因此,按照您的示例,您的 AView.m 文件应命名为 AView.mm。就这么简单。它运作得很好。我在 iPhone 项目中使用了很多 std 容器(std::vector、std::queue 等)和遗留的 C++ 代码,没有任何复杂性。

关于c++ - 混合 Objective-C 和 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15185942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com