解決 assignment discards 'const' qualifier from pointer target type 的問題


 

float fr = external_library_function(...)

用上述語句調用外部庫函數 "external_library_function" 編譯時總是報 

warning:assignment discards 'const' qualifier from pointer target type
 
查看調用的函數源碼發現其定義為
const float *external_library_function(...)

這種情況說明該函數返回的是一個指向常量或變量的指針,修改十分容易,只需要將 "fr"  的定義改為 const float,

const float fr = external_library_function(...)

問題解決了,但還是要進一步思考指針和 const 一起用時的幾個注意點:

1. const float *p  p 是指向常量或變量的指針, 指向可以改變。

e.g.

const float f1 = 1.0, f2 = 2.0;
const float *p = &f1;
cout<<"*p = "<< *p <<endl;
*p = 3.0; /* error: p 指向 f1, f1 是常變量不能更改*/ 
p = &f2; /*correct: p 的指向可以更改*/
cout<<"*p = "<< *p <<endl;

輸出結果:

*p = 1
*p = 2

 

2. float *const p  p不可以指向常量或常變量,指向確定后不可更改。

e.g.

float f1 = 1.0, f2 = 2.0;
float *const p = &f1;
*p = 3.0; /* correct: p 指向 f1, f1 可以更改, f1 的值變為 3.0*/ 
cout<<"*p = "<< *p <<endl;
cout<<"f1 = "<< f1 <<endl;
p = &f2; /*error: p 的指向不可以更改*/

輸出結果:

*p = 1
f1 = 3

3. const float *const p p可以指向常量或變量,指向確定后不可更改。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM