Tôi đang cố gắng kết hợp Objective-C với C++. Khi tôi biên dịch mã, tôi nhận được một số lỗi.Trộn Objective-C và C++
A.h
#import <Cocoa/Cocoa.h>
#include "B.h"
@interface A : NSView {
B *b;
}
-(void) setB: (B *) theB;
@end
giờ sáng
#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++";
}
};
Sau đây là các lỗi:
/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)
Đừng quên rằng bạn buộc người dùng của lớp ObjC của bạn để sử dụng ObjC++ nếu bạn đặt C++ bao gồm trong tiêu đề - sử dụng con trỏ đục để tránh điều đó. –
@gf Vì vậy, bạn sẽ khuyên bạn nên làm điều này như thế nào? Tôi có nên sử dụng một con trỏ void, hoặc tôi có thể sử dụng một loại id? – LandonSchropp
Để tránh mất an toàn loại cá nhân tôi thích các cấu trúc được khai báo trước (http://stackoverflow.com/questions/2262011/adding-c-object-to-objective-c-class/2262395) nhưng cũng đã thấy * "riêng tư" * Các lớp ObjC (tức là thông qua các biến mẫu 'id'). –