Function overloading in C ++ (constant pointers)

Consider the following code snippets:

void foo(const int i) // First foo
{
   std::cout << "First " << i << endl;
}

void foo(int i)       // Second foo
{
   std::cout << "Second " << i << endl;
}

int main() 
{
   int i = 5;
   foo(i);      
}

Compilation Error: redefinition of 'void foo(int)'

Since it constcan not be initialized with objects const, the above behavior seems reasonable. Now consider the following:

void foo_ptr(const int* p)  // First foo_ptr
{
   std::cout << "First " << *p << endl;
}

void foo_ptr(int* p)        // Second foo_ptr
{
   std::cout << "Second " << *p << endl;
}

int main()
{
   int i = 5;
   foo_ptr(&i);             // Second foo_ptr gets called; prints 'Second 5'
}

How can this be clear, my question is: if the two definitions fooin the first case are considered the same, then why is this not the case foo_ptrin the second case? Or, in other words, why is it constignored in the first case, and not in the second?

+4
source share
4 answers
const int* p

, (.. [const int] * p, const [int * p]). :

const int * const p;

, - p, , , , .

, , , . , i const.

, const - , , . "pointer to int" " const int" .

:

void foo_ptr (int * const p)
void foo_ptr (int * p)
+3

const volatile , , . ++, ยง 13.1.3.4:

, const / . - , , , . [ :

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] ; const volatile-, . , T, " T", " const T" " " , " to T," " const T" " volatile T."

+1

const , ?

const , const pointee, . const - .

const -const . const, .. int* const p vs int* p, , .

0

,

void foo(const int n)
{
}

, const, n foo(). foo() - int. const . ,

void foo(int n)

void foo(const int n)

- , int. , , , non const .

void foo(const int *p)

void foo(int *p)

- const, - . .

:

void foo(int *p)

void foo(int * const p)

have the same type of parameter. The parameter of both functions is a pointer to int. Except that the second parameter is a value const, and the function cannot change it.

Not confused yet?

0
source

All Articles