objective-c++: is it possible to define a c++ class with a method which returns objective-c classes and uses covariant returns?
**Edit: this only happens with llvm; gcc supports this just fine.
Consider the following.
Objective-c classes A and B.
B开发者_如何学JAVA 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.
This compiles and runs fine for me:
#import <Cocoa/Cocoa.h>
@interface A : NSObject
- (NSString*) bar;
@end
@implementation A
- (NSString*) bar
{
return @"";
}
@end
@interface B : A
@end
@implementation B
- (NSString*) bar
{
return @"!!!";
}
@end
class X {
//...
public:
virtual A* getFoo() = 0;
};
class Y : public X {
//...
public:
virtual B* getFoo() { return [B new]; }
};
int main (int argc, char const *argv[])
{
X* x = new Y;
NSLog(@"%@", [x->getFoo() bar]); // >> !!!
return 0;
}
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.
精彩评论