简体   繁体   中英

Differing types in declaration and definition in C++

I was going through a piece of code and found a strange thing. A function was declared as follows:

void func(int, int*);

but then it was defined as

void func(int a, int &p) { ... }

The code is compiling properly in gcc under Linux. How can this be possible?(it has been build as a C file)

#include<iostream>
#include<string>

// overloads, nothing to do with func(int, int&)
int func(int, int*);
int func(int, short);
int func(int, std::string);

int func(int a, int& b) {
    return a;
}

int main() {
  int x;
  std::cout << func(4, x) << std::endl;

  return 0;
}

that is, functions that take different parameters are completely different functions (even if they have the same name). Those functions are said to have a different signature .

The definition and declaration each refer to a different function. More specifically, to a differnt overload of the same function name.

This:

void func(int, int*);

Declares a function taking an int and int* .

This:

void func(int a, int &p) { ... }

Declares and defines a function taking an int and int& . They're different functions. Calling code which sees both will call the appropriate one based on overload resolution as normal.

I couldn't understand clearly your question ,But I guess you are confused in mapping of parameters b/w function call and function definition, Especially pointers. Use a lock and key concept to understand pointers. Suppose p is a pointer variable. &p is its address .

Now assume & is working as a lock . YOu want to access value p is pointing to ,So you need a key .Now I am giving you * key to open your & lock . hence *(&p) will give you the value stored at address p was pointing to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM