C++ member functions with same name and parameters, different return type

后端 未结 5 1935
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 12:28

is it valid if I define member functions with same name¶meters but different return types inside a class like this:

class Test {
public:
    int a;
          


        
5条回答
  •  鱼传尺愫
    2021-01-18 13:06

    is it valid if I define member functions with same name¶meters but different return types [...]?

    No. Neither a method class nor a non-class function.

    The reason is ambiguity. There would be situation in which the compiler could not pick the right overloading only by deducing the returned value.

    In conclusion: you can't overload methods based on return type.


    In your example, those two methods:

     Test& getTest();
     const Test& getTest() const;
    

    Are correctly overloaded because the signature is different, but not because the return value is different!

    Indeed, a function signature is made up of:

    • function name
    • cv-qualifiers
    • parameter types
    • method qualifier

    So the signature of your methods are:

    1) getTest();
    2) getTest() const;
                  ^------ Note that const qualifiers of the method is part of signature
    

    As you can notice, the return value is not part of signature, but the const of the method qualifier is.


    Which member function gets called if we have following code?

    With the following code:

    Foo foo;
    Test& t1 = foo.getTest();
    const Test& t2 = foo.getTest();
    

    It will call only the no-const method, even in the case t2.

    The reason is that foo object is no-const in that scope, so each method will be called in its no-const form.

    In details, in the third line:

    const Test& t2 = foo.getTest();
    

    foo.getTest() will return the no-const reference and after will be implicitly converted in a const reference.

    If you want to force the compiler to call the const version, you should "temporary convert" the object foo in a const.

    For example:

    const int& t2 = static_cast(foo).getTest();
    

    In that case I get a const ref to the object, so the object will be treated like a const and the proper const method will be invoked.

提交回复
热议问题