【发布时间】:2010-04-26 00:21:35
【问题描述】:
我正在尝试将 Objective-C 与 C++ 混合使用。当我编译代码时,我得到了几个错误。
啊.h
#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)
【问题讨论】:
-
不要忘记,如果您将 C++ 包含在标头中,您会强制 ObjC 类的用户使用 ObjC++ - 使用不透明指针来避免这种情况。
-
@gf 那么你会如何推荐这样做呢?我应该只使用 void 指针,还是可以使用 id 类型?
-
为了避免失去类型安全性,我个人更喜欢前向声明的结构 (stackoverflow.com/questions/2262011/…),但也看到了 "private" ObjC 类(即通过
id实例变量)。
标签: c++ objective-c objective-c++