C++类中的Objective C成员

use*_*443 4 c++ function objective-c member

是否可以在c ++类中拥有一个目标c成员

@interface ObjectiveCClass : UIViewController  {

    int someVarialbe;

}
- (void)someFunction;

@end


class CPlusPlusClass{
      ObjectiveCClass obj;          // have a objective c member

      void doSomething(){
           obj.someFunction;        // and call a objective c method
       }
};
Run Code Online (Sandbox Code Playgroud)

真的很感激任何指导.

干杯

Chr*_*cke 7

要创建可以在obj-c和cpp代码之间共享的头文件,可以使用编译器预定义的宏来执行以下操作:

// A .h file defining a objc class and a paired cpp class
// The implementation for both the objective C class and CPP class
// MUST be in a paired .mm file
#pragma once

#ifdef __OBJC__
#import <CoreFoundation/CoreFoundation.h>
#else
#include <objc/objc.h>
#endif

#ifdef __OBJC__

@interface ObjectiveCClass :
...

typedef ObjectiveCClass* ObjectiveCClassRef;

#else

typedef id ObjectiveCClassRef;

#endif

#ifdef __cplusplus

class CPlusPlusClass {
  ObjectiveCClassRef obj;

  void doSomethind();
};

#endif
Run Code Online (Sandbox Code Playgroud)

我不是100%确定它的合法性使ObjectiveCClassRef改变类型,如c/cpp和obj-c之间的类型.但是id,在目标C头文件中定义的ac/cpp兼容类型能够存储目标C类指针,并且当在.m或.mm文件中使用时,允许您使用目标C语法直接调用该对象.