1. 程式人生 > 實用技巧 >解決 assignment discards 'const' qualifier from pointer target type 的問題

解決 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可以指向常量或變數,指向確定後不可更改。