将指针传递给函数 - 为什么我不能打印地址?

Sea*_*son 3 c++ pointers

我不明白为什么我不能打印指针的地址.我知道理解指针是非常基础的,所以任何帮助都会受到赞赏.

void printp(int& test)
{
        cout << test << endl;
}

int main()
{
        int *p = new int;
        *p = 1;
        int np = 0;

//      printp(p);  // why doesn't this print the address of p?
//      printp(&p); // why doesn't this print the address of p?
        printp(*p); // prints 1
        printp(np); // prints 0

return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用'printp(p)'时出现以下错误.

test.cpp: In function ‘int main()’:
test.cpp:17:10: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  printp(p);  // why doesn't this print the address of p?
          ^
test.cpp:5:6: note:   initializing argument 1 of ‘void printp(int&)’
 void printp(int& test)
      ^~~~~~
test.cpp:17:10: error: cannot bind rvalue ‘(int)p’ to ‘int&’
  printp(p);  // why doesn't this print the address of p?
Run Code Online (Sandbox Code Playgroud)

Ric*_*chS 8

您从编译器收到错误消息,因为编译器需要参考参数的确切类型.

当函数具有引用参数时

void printp(int& test);
Run Code Online (Sandbox Code Playgroud)

而不是指针参数,

void printp(int* test);
Run Code Online (Sandbox Code Playgroud)

调用者必须提供确切类型的变量.它不能提供对任何其他类型的变量的引用(除非您可以从其他类型的dynamic_cast到参数的类型).

因此,当您调用时printp(p);,编译器要求p类型int,而不是int *.

如果你传递值,编译器会为你推广或static_cast某些类型,

void printp(int test);
short s = 0;
printp( s ); // s is promoted to int here.
Run Code Online (Sandbox Code Playgroud)

但是当参数是引用时,编译器无法为您执行此操作.