Overloading by return type

前端 未结 11 1860
我在风中等你
我在风中等你 2020-11-22 07:07

I read few questions here on SO about this topic which seems yet confusing to me. I\'ve just begun to learn C++ and I haven\'t studied templates yet or operator overloading

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 07:54

    While most of the other comments on this problem are technically correct, you can effectively overload the return value if you combine it with overloading input parameter. For example:

    class My {
    public:
        int  get(int);
        char get(unsigned int);
    };
    

    DEMO:

    #include 
    
    class My {
    public:
        int  get(         int x) { return 'I';  };
        char get(unsinged int x) { return 'C';  };
    };
    
    int main() {
    
        int i;
        My test;
    
        printf( "%c\n", test.get(               i) );
        printf( "%c\n", test.get((unsigned int) i) );
    }
    

    The resulting out of this is:

    I 
    C
    

提交回复
热议问题