从目标c调用目标c++方法



我只是在学习Objective C(以及Objective-C++),我有一个Objective-C++类,它具有以下构造函数。

void InputManager::_init (int inputAreaX, int inputAreaY, int inputAreaWidth, int inputAreaHeight)

我如何从目标C调用它?

这似乎是一个纯C++方法,因此它的工作方式与普通C++完全相同(甚至在Objective-C++文件中)。例如,您可能在堆栈上定义了一个变量:

InputManager mgr; // or, include constructor arguments if the class can't be default-constructed
mgr._init(x, y, w, h); // this assumes 4 variables exist with these names; use whatever parameter values you want

_init这个名字有点奇怪;你的意思是说这是类的构造函数吗?如果是这样,则可能应该定义InputManager::InputManager(int x, int y, int w, int h)

如果您真的希望这个类仅为Objective-C,那么语法和行为是不同的。

您有两个选项:

选项1。

将其转换为仅限Objective-C的代码。我不太擅长C++,但这可能就是它在.h:中的样子

-(id)initWithAreaX: (int) inputAreaX AreaY: (int) inputAreaY AreaWidth: (int) inputAreaWidth AreaHeight: (int) inputAreaHeight;

由于它看起来像是一个构造函数方法,所以在实现中可能会是这样的:

-(id)initWithAreaX: (int) inputAreaX AreaY: (int) inputAreaY AreaWidth: (int) inputAreaWidth AreaHeight: (int) inputAreaHeight {
    self = [super init];
    if(self) {
        //Custom Initialization Code Here    
        _inputAreaX = inputAreaX;
        _inputAreaY = inputAreaY;
        _inputAreaWidth = inputAreaWidth;
        _inputAreaHeight = inputAreaHeight;
    }
    return self;
}

你可以这样称呼它:

InputManager *object = [[InputManager alloc] initWithAreaX: 20 AreaY: 20 AreaWidth: 25 AreaHeight: 25];

选项2.

Objective-C++的全部目的是允许开发人员集成C++和Objective-C代码。你想知道如何从Objective-C中调用Objective-C++方法,但Objective-CC++的全部目的是集成两者,所以在一个完全是Objective-C的文件中找漏洞调用Objective-C++方法是没有意义的。因此,第二种选择是在扩展名为".mm"的Objective-C++文件中创建要调用Objective-CC++方法的文件。

希望这能有所帮助!

最新更新