0

我见过许多不同的写地址运算符 (&) 和间接运算符 (*) 的方法

如果我没记错的话应该是这样的:

//examples
int var = 5;
int *pVar = var;

cout << var << endl; //this prints the value of var which is 5

cout << &var << endl; //this should print the memory address of var

cout << *&var << endl; //this should print the value at the memory address of var

cout << *pVar << endl; //this should print the value in whatever the pointer is pointing to

cout << &*var << endl; //I've heard that this would cancel the two out

例如,如果您在两者之间写一个空格,会发生&var什么& var?我见过的常见语法:char* line = var;, char * line = var;, 和char *line = var;.

4

1 回答 1

1

第一int *pVar = var;不正确;这不存储的地址var,但它存储地址“5”,这将导致编译错误说:

main.cpp: In function 'int main()':
main.cpp:9:15: error: invalid conversion from 'int' to 'int*' [-fpermissive]
    int *pVar = var;
                ^~~

var需要在初始化时引用*pvar

int *pVar = &var;

其次,由于不是指针( )类型变量,cout << &*var << endl;也会导致编译出错:varint*

main.cpp: In function 'int main()':
  main.cpp:19:13: error: invalid type argument of unary '*' (have 'int')
     cout << &*var << endl; //I've heard that this would cancel the two out
               ^~~

现在,要回答您的问题,在引用 ( &) 运算符和指针 ( *) 运算符之间添加空格对编译器绝对没有影响。唯一不同的是当你想分开 2 个令牌时;像conststring例如。运行以下代码只是为了夸大您所要求的示例:

cout <<             &             var << endl;  
cout <<                            *                    & var << endl;
cout <<                                   *pVar << endl;

产生与没有太多空格的代码相同的结果:

0x7ffe243c3404
5
5
于 2017-04-08T02:17:22.007 回答