functions with const arguments Overloading ( Follow up)

后端 未结 6 1673
野的像风
野的像风 2020-12-20 08:30

This is a follow up of the Previous Question

It got really complicated so I am starting a new thread to make my point clearer.( Didnt want to delete the previous thr

6条回答
  •  离开以前
    2020-12-20 08:45

    The call of const (or non-const) function doesn't depend of the constness of the parameters but only of the constness of the called object (in our case obj). Overload needs different type and (non-const const) are not, so I don't think you can overload as you are doing it. (that work because you are defining a const and a non-const methods but that's not overloading.) To persuade yourself, try to remove the const at the end of your declaration to see if you are allowed to declare

    int foo(int a);
    int foo(const int a);
    

    You'll get an error.

    In the second case you think foo is expecting a const int as argument but not. const is tied to a not to int. So what it says is foo expect an int, you could refer it using a and that will be const : you are not allowed to modify a. That's why the const (of a parameter) doesn't appear in the function signature (that would be different for a reference).
    The const outside the function refers to object called , so that's part of the signature

    int foo(int a); # type => int (Test::*)(int)
    int foo(const int a) const; # => int (const Test::*)(int)
    
    int foo(const int a) ; # => int (Test::*)(int)
    int foo(int a) const; # => int (const Test::*)(int)
    

    (I'm not 100% sure about the type syntax , so don't comment on it, that's just to give an idea)

    As you can see the const get removed with a. You can also write it int const a, even if not the standard way to do it, it's perfectly legal.

    By the way , your code will never do what you are expected, you should use a reference to an int to modify it

    int Test::foo(int &a) ...
    

提交回复
热议问题