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