concept of overloading in C++

前端 未结 3 1828
情话喂你
情话喂你 2021-01-28 03:48

case 1: you can overload two functions namely:

void foo(int *);
void foo(const int *);

while in , case 2: you can not overload two functions:

相关标签:
3条回答
  • In the second case, because integers are primitive type, the int or const int is passed by value, and the function makes a copy of the variable. Therefore, the function definition is the same.

    In the first case, the first function takes in an integer pointer as a parameter, whereas the second function takes in a pointer to a constant integer. These are different data types, as the value of the integer is not copied by the value of the pointer is, and therefore the data is passed by reference.

    0 讨论(0)
  • 2021-01-28 04:09

    Top level CV qualifications for formal arguments are ignored wrt. determining the function's type.

    (CV: const or volatile)

    One way to understand it is, there is no way a top level CV qualification of a formal argument can affect a caller of the function, and it can't affect the machine code. It's only about restrictions on the implementation. So given a declaration void foo( int ) you can use void foo( const int ) for the implementation, or vice versa, if you want.

    0 讨论(0)
  • 2021-01-28 04:29

    From Standard §13.1

    Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. [ Example:

    typedef const int cInt;
    int f (int);
    int f (const int); // redeclaration of f(int)
    int f (int) { /* ... */ } // definition of f(int)
    int f (cInt) { /* ... */ } // error: redefinition of f(int)
    

    —end example ]

    Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations. In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

    0 讨论(0)
提交回复
热议问题