c++ - 引用指针(int * const和arg)

标签 c++ pointers reference

这到底是什么:

int * const & arg

这是
  • 对int指针的引用?
  • 对const int指针的引用?
  • 一个指向int指针的const引用?
  • 对const int指针的const引用?

  • 顺便说一句,const引用对我没有任何意义。我以为您不能在引用声明后更改它们。

    最佳答案

    arg是对 int指针引用,其中该指针本身是恒定的。

    声明arg时,您会注意到(因为它是一个引用)它必须被初始化,因为引用不能引用任何内容。

    一个简单的方法是使用一个示例:

    int x;
    int* const ptr = &x;
    // declare an integer pointer which is constant i.e. the address it stores does not change,
    // and initialize this address to the address of x
    
    int* const& arg = ptr;
    // declare a reference variable called arg, which references an integer pointer which is constant,
    // the same type that ptr is, and then make it reference our ptr variable
    

    由于 const 参数在代码行中的“*”之后,因此您要告诉C++指针本身是常量。但是,如果我们要写
    const int* & arg = ...
    

    要么
    int const* & arg = ...
    

    我们会告诉C++,指针指向的数据是常量(在这种情况下为整数)。此外,如果我们写了以下内容
    int const* const & arg = ...
    

    我们会告诉C++,指针存储的地址是常量,并且该地址指向一个也是常量的整数。

    希望这对您有所帮助!

    关于c++ - 引用指针(int * const和arg),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61257493/

    相关文章:

    C++成员函数指针指向全局函数指针

    c++ - 在应该按引用传递的地方按值传递指针

    c++ - luabind::object 取消引用的问题(简化)

    c++ - 具有分配语义的非拥有者

    c++ - 将引用用作数组/指针是否合法?

    c++ - 将渲染目标数据复制到 D3DPOOL_MANAGED?

    c++ - C++ 中 void(*)() 和 void(&)() 的区别

    c - Valgrind 结果干净但分配多于释放

    c - 在c中的链表中插入一个条目

    c++ - 将 std::function* 传递给模板参数