我不明白为什么我不能打印指针的地址。我知道理解指针是非常基础的,所以任何帮助都是非常感谢的。
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;
}当我尝试使用'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?发布于 2017-08-26 08:12:06
您从编译器获得错误消息,因为编译器需要引用参数的确切类型。
当函数有引用参数时
void printp(int& test);代替指针参数,
void printp(int* test);调用方必须提供确切类型的变量。它不能提供对任何其他类型的变量的引用(除非您可以从另一种类型dynamic_cast到参数的类型)。
因此,当您调用printp(p);时,编译器要求p的类型为int,而不是int *。
如果您通过值传递,编译器将为您提升或static_cast某些类型。
void printp(int test);
short s = 0;
printp( s ); // s is promoted to int here.但是,当参数是引用时,编译器不能为您做这件事。
发布于 2017-08-26 08:13:45
在你的代码中,printp(int&)是一个接受引用而不是指针的函数,所以在你的例子中,要获得指针的地址,你可以简单地改变它或重载它:
void printp(int* test){
cout << test << endl; // the addres test contains not its address
cout << &test << endl; // the address of test itself
cout << *test << endl; // the value in the address that test points to
}在main中:
printp(p);输出:
00893250
0018FEEC
1发布于 2017-08-26 08:40:42
对于int a;
expr | type
-----+-----
&a | int*
a | int
*a | - (not valid)对于int* p;
expr | type
-------+-----
&p | int**
p | int*
*p | int
**p | - (not valid)对于int** pp;
expr | type
-------+-----
&pp | int***
pp | int**
*pp | int*
**pp | int
***pp | - (not valid)https://stackoverflow.com/questions/45890732
复制相似问题