concept of overloading in C++

自闭症网瘾萝莉.ら 提交于 2020-01-11 13:50:16

问题


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:

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

I have coded and checked this concept and yet unable to find out the reason to this variation in overloading.


回答1:


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.”




回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/28491974/concept-of-overloading-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!