解决 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