參數const XX* pXX與參數const XX& xx的注意點
編者:李國帥
qq:9611153 微信lgs9611153
時間:20
背景:
VC中指針和引用是容易出錯的地方,說起來簡單,用起來需要小心;靈活運用可以避免錯誤。
const XX*只能保證指針pXX不被改變,不能保證裏面的數據不被改變
const XX& xx參數可以保證對象xx內部數據不能改變
總結:
typedef struct xx
{
int a;
unsigned char * b;
}XX;
int func(const XX* pXX)//const XX*只能保證指針pXX不被改變,不能保證裏面的數據不被改變
{
strcpy((char*)pXX->b,"54321");//成員的優先級高於前置括號,一定要小心。
pXX = NULL;//僅僅是副本指針變化,原件沒有變化
return 0;
}
int funcObject(const XX& xx)
{
//strcpy(xx.b,"54321");//錯誤不能改變整個對象
//xx.a = 0;
return 0;
}
int main(int argc, char* argv[])
{
xx stcc;
stcc.b = new unsigned char[10];
strcpy((char*)stcc.b,"12345");
//const char* p = (char*)stcc.b;
//cout<<p<<endl;
func(&stcc);
delete stcc.b;//"54321"
system( "PAUSE" );
return 0;
}