在 C++ 中将指针变量分配给 const int?
我想知道是否有人可以向我解释以下内容:如果我写,
int i = 0;
float* pf = i;
我会收到编译错误(gcc 4.2.1):
error: invalid conversion from ‘int’ to ‘float*’
有道理 - 它们显然是两种完全不同的类型。但如果我写
const int i = 0;
float* pf = i;
它编译没有错误。为什么“const”在赋值的右侧会产生影响? “const”关键字的想法不就是能够对常量值强制类型约束吗?
我能想到的任何解释都感觉有点虚假。 事实
const int i = 1;
float* pf = i;
而且我的解释都没有解释无法编译的 。有人能提供解释吗?
I'm wondering if anyone can explain the following to me: If I write
int i = 0;
float* pf = i;
I get a compile error (gcc 4.2.1):
error: invalid conversion from ‘int’ to ‘float*’
Makes sense - they are obviously two completely different types. But if instead I write
const int i = 0;
float* pf = i;
It compiles without error. Why should the 'const' make a difference on the right hand side of the assignment? Isn't part of the idea of the 'const' keyword to be able to enforce type constraints for constant values?
Any explanation I have been able to come up with feels kind of bogus. And none of my explanations also explain the fact that
const int i = 1;
float* pf = i;
fails to compile. Can anyone offer an explanation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第二个示例恰好包含在 §4.10/1 (C++03) 中指定的转换规则中:
Your second example simply happens to be covered by the conversion rules as specified in §4.10/1 (C++03):