【问题标题】:What is the correct format for the address (&) and indirection operator [closed]地址(&)和间接运算符的正确格式是什么[关闭]
【发布时间】:2017-04-08 00:48:03
【问题描述】:

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

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

//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

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

【问题讨论】:

  • 你试过了吗?
  • 在此区域中,空格仅在用于分隔标记时才有意义。例如,如果您有char const *foo,则需要在charconst 之间留出空格(以防止将其视为单个令牌charconst),但其余无关紧要-您可以删除或者在* 的每一侧插入尽可能多的空格,这对含义没有影响(&amp; 也是如此)。对于如何使用空白可以最大限度地提高可读性,存在广泛的不同意见。
  • 现代编译器应该停在这里:int *pVar = var;。整数不是指针。 (这在 C 中是合法的,但我的 C++ 并没有回溯到足以确定它在 C++ 中是否合法)所有编译器都应该拒绝 &amp;*var 因为在应用 &amp; 之前它将应用 * 而你只能*,解引用,指针。

标签: c++ pointers addressof


【解决方案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 &lt;&lt; &amp;*var &lt;&lt; endl;也会导致编译出错,因为var不是指针(int*)类型变量:

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
               ^~~

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

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

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

0x7ffe243c3404
5
5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-06
    • 2014-01-14
    • 1970-01-01
    • 2015-09-02
    • 2011-02-04
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多