Overloading by return type

前端 未结 11 1901
我在风中等你
我在风中等你 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:34

    Resurrecting an old thread, but I can see that nobody mentioned overloading by ref-qualifiers. Ref-qualifiers are a language feature added in C++11 and I only recently stumbled upon it - it's not so widespread as e.g. cv-qualifiers. The main idea is to distinguish between the two cases: when the member function is called on an rvalue object, and when is called on an lvalue object. You can basically write something like this (I am slightly modifying OP's code):

    #include 
    
    class My {
    public:
        int get(int) & { // notice &
            printf("returning int..\n");
            return 42;
        }
        char get(int) && { // notice &&
            printf("returning char..\n");
            return 'x';
        };
    };
    
    int main() {
        My oh_my;
        oh_my.get(13); // 'oh_my' is an lvalue
        My().get(13); // 'My()' is a temporary, i.e. an rvalue
    }
    

    This code will produce the following output:

    returning int..
    returning char..
    

    Of course, as is the case with cv-qualifiers, both function could have returned the same type and overloading would still be successful.

提交回复
热议问题