我正在混合使用 Objective-C 和 C++。但是我想尽量减少使用 Objective-C++。因为它在 Objective-C 和 C++ 中都有某种限制。
目前,我是这样使用的。
// A.h, Objective-C
#import "B.h"
@interface A
{
B* b;
}
@end
// B.h, Objective-C++
@interface B
{
void* c;
}
// C.h, C++
class C
{
};
我想在B.h
中包含C.h
,但是如果我这样做了,B.h
不能导入到A.h
中>。所以我必须将变量 c
保留为 void*
类型。这不是一个大问题,因为我可以在 B.m
文件中自由使用 C
的成员。但我总是必须施放它。这感觉有些不明朗。所以我想使用更好的方法。
最佳答案
有几种方法可以做到这一点,但我认为最好的方法是使用 'PIMPL' idiom ,这在 C++ 中相当常见。使 header 成为纯 Objective-C 和纯 C++,并带有指向包含实际实现的前向声明结构的指针。这是在 .mm 文件中定义的,然后可以使用 Objective-C++。
在你的例子中,你会做这样的事情:
// B.h, pure Objective-C:
struct BImpl;
@interface B
{
struct BImpl* impl;
}
// ...
// B.mm, mixed:
#include "C.h"
struct BImpl // since this is C++, it can actually have constructors/destructors
{
C* my_c;
BImpl() : my_c(new C) {}
~BImpl() { delete my_c; my_c = NULL; }
};
// make sure to alloc/initialise impl (using new) in B's init* methods,
// and free it (using delete) in the dealloc method.
我实际上已经写了一篇关于解决这个问题的文章,你可能会发现它很有用:http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects - 它还展示了一些其他的方法,包括您原来的 void*
方法。
关于c++ - 将 C++ 类用于 Objective-C 类的推荐方法最小化对 Objective-C++ 的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448754/