在Objective-C代码中使用Objective-C++类和C++实例变量

4 c++ objective-c objective-c++

我正在编写一个Objective-C++类接口,它必须可以从Objective-C和Objective-C++中使用.问题是,因为它必须可以从Objective-C中使用,所以我不能简单地使用C++类型.我想用指针做它,我想出了这个:

@interface SXDiff : NSObject {
@private
#ifdef __cplusplus
  dtl::Diff<std::string, std::vector<std::string> > *_diff;
#else
  void *_diff;
#endif
}

...

@end
Run Code Online (Sandbox Code Playgroud)

这样做会出现任何问题吗?有没有更好的方法呢?


请注意,使用指针只是为了使Objective-C和Objective-C++中的ivar大小相同.ivar只能在SXDiff(它的@private)类实现中使用.该实现是用Objective-C++编写的.

Joe*_*Joe 5

使用Apple LLVM版本2.0+尝试将标题中的所有C++代码移动到类扩展中.

//SXDiff.h
@interface SXDiff : NSObject {
}

...

@end
Run Code Online (Sandbox Code Playgroud)


//SXDiff.mm
#include "dtl/dtl.hpp"

@interface SXDiff()
{
    dtl::Diff<std::string, std::vector<std::string> > *_diff;
}
@end

@implementation SXDiff

...

@end
Run Code Online (Sandbox Code Playgroud)