Objective-c++:是否可以定义一个 c++具有返回 Objective-C 类并使用协变返回的方法的类?
**编辑:这只发生在 llvm 上; gcc 很好地支持这一点。
请考虑以下事项。
Objective-c 类 A 和 B。
B 是 A 的子类
。我们想要一个如下所示的 C++ 层次结构:
class X {
//...
public:
virtual A* getFoo();
};
class Y : public X {
//...
public:
B* getFoo();
};
但是,如果这样做,您会收到错误,因为 Objective-c 类型会混淆 C++ 编译器:
error: virtual function 'getFoo' has a different return type ('Y *') than the function it overrides (which has return type 'X *')
I想知道是否有人有解决方法? (显然,从长远来看,我们将放弃 Objective-c 类,但那不是今天)。
PS 这个似乎是我能找到的最相似的问题,但我很确定这是一个不同的问题。
**Edit: this only happens with llvm; gcc supports this just fine.
Consider the following.
Objective-c classes A and B.
B is a subclass of A.
We want a c++ hiearchy that looks like:
class X {
//...
public:
virtual A* getFoo();
};
class Y : public X {
//...
public:
B* getFoo();
};
However, if you do this, you'll get an error, as the Objective-c types confuse the c++ compiler:
error: virtual function 'getFoo' has a different return type ('Y *') than the function it overrides (which has return type 'X *')
I'm wondering if anyone has a workaround for this? (Obviously, long term, we'll be moving away from Objective-c classes, but that's not today).
P.S. This seems like the most similar question I could find, but I'm pretty sure it's a different problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对我来说编译和运行良好:
也许你的问题是你没有将 B 的头文件导入到定义 Y 的文件中?您无法在不完整的类上获得协方差(至少在 C++ 中),因为编译器需要知道 B 继承自 A 才能编译 Y。
无论如何,为了回答您的问题,看起来可以做到这一点。
This compiles and runs fine for me:
Maybe your problem was that you didn't import B's header file into the file defining Y? You can't get covariance (in c++, at least) on incomplete classes, as the compiler needs to know that B inherits from A in order to compile Y.
Anyway, to answer your question, looks like it is possible to do this.