gpt4 book ai didi

c++ - 常量的引用和指针有什么用?

转载 作者:太空狗 更新时间:2023-10-29 22:54:28 25 4
gpt4 key购买 nike

在 C++ Primer 一书中,我读到了对常量的引用,例如:

const int ci = 1024;
const int &r1 = ci;

指针也是如此。

const double pi = 3.14;
const double *ptr = π

我想知道,如果你连常量的值都不能改变,那么这些引用有什么用呢?为什么您甚至想要创建指向常量的指针?

最佳答案

I wonder, what is the usage of these references if you can't even change the value of the constant

最常见的用例是函数。带有参数的函数可能比仅使用常量的函数有用得多。

但是将常量传递给函数调用(从而将参数绑定(bind)到该常量)也很有用:

void foo(const int &r1);

// call using a constant
foo(ci);

请注意,很少需要使用对整数的引用,因为通常人们只对整数的值感兴趣,而不关心对象的身份。

引用和指针提供的间接性使得运行时多态性成为可能。当您学习面向对象编程时,您会了解到这一点。

关于c++ - 常量的引用和指针有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com