从Objective-C类调用C ++构造函数 [英] Call a C++ constructor from an Objective-C class

查看:106
本文介绍了从Objective-C类调用C ++构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Objective-C类内部调用C ++构造函数?

How can I call a C++ constructor from inside an Objective-C class?

class CppClass {
public:
    CppClass(int arg1, const std::string& arg2): _arg1(arg1), _arg2(arg2) { }

    // ...
private:
    int _arg1; std::string _arg2;
};

@interface ObjC: NSObject {
    CppClass _cppClass;
}
@end

@implementation ObjC

- (id)init
{
    self = [super init];
    if ( self )
    {
         // what is the syntax to call CppClass::CppClass(5, "hello") on _cppClass?
    }
    return self;
}
@end

推荐答案

当我遇到默认构造函数无法剪切的情况时,我将实例变量设置为指针,然后在init方法和dealloc方法中的delete.

When I end up in a situation where the default constructor doesn't cut it, I make the instance variable a pointer and then use new in the init method and delete in the dealloc method.

实际上,对于Objective-C实例变量完全调用默认构造函数是一门相对较新的事情.

It's a relatively recent thing that default constructors are called at all for Objective-C instance variables, actually.

没有Objective-C语言的规范,更不用说Objective-C ++扩展的规范了.苹果确实发布了名为 Objective-C编程语言,但是它几乎没有提到C ++,因此当您需要澄清一些不明显的内容时,您通常会独自一人. Clang 的家伙

There is no specification of the Objective-C language, let alone a specification of the Objective-C++ extension. Apple does publish a document called The Objective-C Programming Language, but it barely mentions C++, so you're often left on your own when you need to clarify something unobvious. The guys at the Clang mailing list often know better, though.

这篇关于从Objective-C类调用C ++构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆