Can I overload an operator in Objective-C?

后端 未结 7 578
萌比男神i
萌比男神i 2020-12-15 15:02

Is it possible to override operator use in Objective-C?

For example

myClassInstance + myClassInstance

calls a custom function to ad

7条回答
  •  执念已碎
    2020-12-15 15:49

    I know this is an old question but I just wanted to leave this answer here for anybody in the future that might want to know if this is a possibility.

    The answer is YES!

    You'll have to use a variant of Objective-C called Objective-C++. As an example, say you created a new Objective-C command-line tool project. In order to allow C++ functionality, you'll need to rename "main.m" to "main.mm". Afterwards, you can mix C++ code in with your Objective-C code in the same file. There are some limitations, but I've tested operator overloading and it seems to work perfectly fine with Objective-C objects as far as I can tell. I've included sample source code to give you an idea of how to do it:

    //main.mm
    #import 
    #include 
    #include 
    
    std::ostream &operator<<(std::ostream &os, NSString *s) {
        os << [s UTF8String];
        return os;
    }
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
    
            NSString *str = @"I'm an NSString!";
            std::cout << str << std::endl;
    
        }
        return 0;
    }
    

    Here's my output after building and running this code:

    I'm an NSString!
    Program ended with exit code: 0
    

    Hopefully this will be of help to somebody!

提交回复
热议问题