address-of运算符:&
& cast-expression
备注
一元 address-of 运算符 () 获取其操作数地址。 操作数 address-of 运算符可以是操作指示符或指定对象不是位域和未声明的 注册 存储类说明符的左值。
address-of 运算符仅适用于基础知识、结构、类或声明在文件范围级别的联合类型的变量,或对 subscripted 引用数组。 在这些表达式,不包括运算符地址的常数表达式中添加或从中减去地址表达式。
当应用于函数或左值,该表达式的结果是从该操作数的类型 (r 值) 派生的指针类型。 例如,在中,如果操作数是类型 char,表达式的结果是类型的指针。 char。 address-of 运算符,会应用于 const 或 volatile 对象,因此计算结果为 const type * 或 volatile type *,其中 type 是原始对象的类型。
当地址运算符应用于 限定名时,结果取决于该 限定名称 是否指定静态成员。 如果存在,则结果是指向在成员的声明中指定的类型。 如果该成员不是静态的,则结果是指向 限定类名称表示类的成员的 名字 。 (有关更多 主表达式 参见有关 限定类名称。)下面的代码片段演示了结果如何有所不同,该成员是否为静态函数:
// expre_Address_Of_Operator.cpp
// C2440 expected
class PTM {
public:
int iValue;
static float fValue;
};
int main() {
int PTM::*piValue = &PTM::iValue; // OK: non-static
float PTM::*pfValue = &PTM::fValue; // C2440 error: static
float *spfValue = &PTM::fValue; // OK
}
在此示例中,,因为 fValue 是静态成员,表达式 &PTM::fValue 给定类型 float * 而不是类型 float PTM::* 。
一个重载函数的地址可以执行时,才显示该功能的版本引用的明确时。 有关如何获取特定重载函数的地址的信息,请参见 重载函数地址 。
address-of 运算符应用于引用类型生成结果和应用运算符相同于引用了的对象。 例如:
示例
// expre_Address_Of_Operator2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main() {
double d; // Define an object of type double.
double& rd = d; // Define a reference to the object.
// Obtain and compare their addresses
if( &d == &rd )
cout << "&d equals &rd" << endl;
}
Output
&d equals &rd
下面的示例使用 address-of 运算符通过指针参数传递给函数:
// expre_Address_Of_Operator3.cpp
// compile with: /EHsc
// Demonstrate address-of operator &
#include <iostream>
using namespace std;
// Function argument is pointer to type int
int square( int *n ) {
return (*n) * (*n);
}
int main() {
int mynum = 5;
cout << square( &mynum ) << endl; // pass address of int
}
Output
25