C++类作为Objective-C类的实例变量

zou*_*oul 5 c++ objective-c objective-c++

我需要混合使用Objective-C和C++.我想隐藏一个类中的所有C++内容,并保持其他所有内容的Objective-C.问题是我想要一些C++类作为实例变量.这意味着它们必须在头文件中被提及,其被其他类包含并且C++开始传播到整个应用程序.到目前为止,我能够提供的最佳解决方案如下所示:

#ifdef __cplusplus
#import "cppheader.h"
#endif

@interface Foo : NSObject
{
    id regularObjectiveCProperty;
    #ifdef __cplusplus
    CPPClass cppStuff;
    #endif
}

@end
Run Code Online (Sandbox Code Playgroud)

这有效.实现文件有一个mm扩展,因此它被编译为Objective-C与C++混合,#ifdef解锁C++的东西,然后我们去.当其他一些纯粹的Objective-C类导入头时,C++的东西被隐藏起来,而且类没有看到任何特殊的东西.这看起来像一个黑客,有更好的解决方案吗?

Bar*_*ark 8

这听起来像是接口/ @协议的经典用法.为API定义objective-c协议,然后使用Objective-C++类提供该协议的实现.这样客户端只需要知道协议而不是实现的头部.所以给出了最初的实现

@interface Foo : NSObject
{
    id regularObjectiveCProperty;
    CPPClass cppStuff;

}

@end
Run Code Online (Sandbox Code Playgroud)

我会定义一个协议

//Extending the NSObject protocol gives the NSObject
// protocol methods. If not all implementations are
// descended from NSObject, skip this.
@protocol IFoo <NSObject>

// Foo methods here
@end
Run Code Online (Sandbox Code Playgroud)

并将原始Foo声明修改为

@interface Foo : NSObject <IFoo>
{
    id regularObjectiveCProperty;
    CPPClass cppStuff;
}

@end
Run Code Online (Sandbox Code Playgroud)

然后客户端代码可以使用类型id<IFoo>,不需要编译为Objective-C++.显然,您可以将实例传递Foo给这些客户端.