加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 通过引用传递const指针

发布时间:2020-12-16 05:27:19 所属栏目:百科 来源:网络整理
导读:我很困惑,为什么以下代码无法编译 int foo(const float* a) { return 0;}int main() { float* a; foo(a); return 0;} 编译器给出错误: error: invalid initialization of reference of type ‘const float*’ from expression of type ‘float*’ 但是当我
我很困惑,为什么以下代码无法编译
int foo(const float* &a) {
    return 0;
}
int main() {
    float* a;
    foo(a);

    return 0;
}

编译器给出错误:

error: invalid initialization of reference of type ‘const float*&’ from expression of type ‘float*’

但是当我尝试在foo中通过引用时,它正在编译很好.

我认为它是否应该表现出相同的行为,无论我是否参考.

谢谢,

解决方法

因为它不是类型安全的.考虑:
const float f = 2.0;
int foo(const float* &a) {
    a = &f;
    return 0;
}
int main() {
    float* a;
    foo(a);
    *a = 7.0;

    return 0;
}

任何非常量引用或指针必须在指向类型中是不变的,因为非常量指针或引用支持读取(协方差操作)和写入(逆变器操作).

必须先从最大间接级别添加const.这将工作:

int foo(float* const &a) {
    return 0;
}
int main() {
    float* a;
    foo(a);

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读