讲解C++编程中Address-of运算符&的作用及用法
语法 & cast-expression 备注 // 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::*。 // 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |