【问题标题】:Forward declare a C++ class in an objective-C++ file?在目标 C++ 文件中前向声明 C++ 类?
【发布时间】:2011-11-26 19:45:51
【问题描述】:

我有一个 Objective-C++ 文件,我有两个类:一个 Objective-C,一个 C++:

@implementation ClassA

....
// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);

@end

class MyClass : public AnotherClass
{
....

};

上面的 C++ 类编译和运行良好,但我想把它移到底部。当我将它移到底部时,我得到了错误:

不完整类型“struct MyClass”的使用无效 'struct MyClass' 的前向声明

不管使用 typedef,struct,@class 我都得不到爱。如何转发声明这个类?

【问题讨论】:

  • 你能展示MyClass在ClassA中的使用吗? class MyClass 是您预先声明 MyClass 的方式,但您可能必须实际给出它的定义才能使用,例如,在 ClassA 的实现中使用该类的方法。
  • 我已经用你的用法更新了这个问题,谢谢,杰西。

标签: objective-c objective-c++


【解决方案1】:

C++ 类的前向声明不允许您使用该类的实例,您可以直接传递它们。 (为了简化示例,我省略了任何 Objective-C。)

class Something;

void function(void)
{
    Something *x;         // Ok
    x = new Something();  // Error
    int z = x->field;     // Error
    x->method();          // Error
}

class Something : public Other { ... };

void function2(void)
{
    Something *x;         // Ok
    x = new Something();  // Ok
    int z = x->field;     // Ok
    x->method();          // Ok
}

您必须在使用类之前将其完整定义。前向声明只允许您使用类的类型声明变量。

所以答案是:你问的是不可能的。(无论如何,将类定义放在顶部有什么问题?)

你仍然可以把方法放在底部:

class Something {
public:
    void method();
};

@implementation ...
...
@end

void Something::method() { ... }

【讨论】:

  • 把定义放在首位没什么错,但除非我不得不这样做,否则我不想这样做。谢谢!
【解决方案2】:

只需在 ClassA 之前添加类 MyClass Prototype。

class MyClass;
....
@implementation ClassA
....

// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);

@end

【讨论】:

  • 你不能在没有类定义的情况下实例化一个类。 (尝试编译代码,它会说,“invalid use of incomplete type”。)
  • 你仍然需要其他方法的原型,是的。
  • 这里的问题class MyClass; 是前向声明。没用,还不如去掉。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2023-03-16
  • 2013-06-02
  • 1970-01-01
  • 2011-07-08
  • 2016-12-17
相关资源
最近更新 更多