Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c+;中常量指针的用途是什么+;? 我是C++初学者,在指针的目的上没有下面的问题,即地址和它指向的值都不能改变( CONSTEVIONEY > 示例 >_C++_Pointers_Reference_Constants - Fatal编程技术网

c+;中常量指针的用途是什么+;? 我是C++初学者,在指针的目的上没有下面的问题,即地址和它指向的值都不能改变( CONSTEVIONEY > 示例 >

c+;中常量指针的用途是什么+;? 我是C++初学者,在指针的目的上没有下面的问题,即地址和它指向的值都不能改变( CONSTEVIONEY > 示例 >,c++,pointers,reference,constants,C++,Pointers,Reference,Constants,示例: int main() { int i = 1; int j = 2; int* const constPoint = &i; *constPoint = 3; // legal constPoint = &j; // illegal const int* constVal = &i; *constVal = 3; // illegal constVal = &j; // legal c

示例:

int main()
{
    int i = 1;
    int j = 2;
    int* const constPoint = &i;
    *constPoint = 3; // legal
    constPoint = &j; // illegal
    const int* constVal = &i;
    *constVal = 3; // illegal
    constVal = &j; // legal
    const int* const constEverything = &i;
    *constEverything = 3; // illegal
    constEverything = &j; // illegal
}
示例中有不同类型的指针。使用
constVal
可以更改地址,使用
constPoint
可以更改基础值。对于
constEverything
,两者都不能执行


对我来说,这样一个指针的目的是通过不断的引用来传递东西。为什么我不应该只使用常量类型&val?对我来说,常量引用似乎容易得多,它使常量类型*const val过时

常量指针之所以有用,主要有两个原因

  • const
    成员函数中的
    const
    指针

  • const
    指针也可以设置为
    nullptr


  • 我的第一个点是有点圆的,<代码>这个< /C>可能是引用类型或代码> const 引用类型,但是引用到了C++标准中,并且任何更改都会被打破。

    指针是C编程语言的残余。C没有引用,因此指针是您唯一的选择。现在您可以自由使用C++中的引用,但是如果您必须使用C API(例如Win32 API),则必须使用指针。p> 传递参数有两种方式:按值传递和按引用传递。Constness在通过引用传递时尤其相关:它指示传递的参数是否可以更改

    在这方面,有两种方法可以在C++中通过引用传递:使用引用(&)或使用指针(*)。在C中,通过引用传递只有一种方法:使用指针(*)

    这样,如果允许C++中的引用引用为代码> const类型和Value/CODE >,那么C中的等价物必须使用指针,导致<>代码> const类型*const Value/Cuth>。您可以定义指针本身的常量(根据我的经验,在C API中经常可以看到)


    不管个人喜好,因为C代码也应该是有效的C++,所以也需要一个基于指针的版本。

    #include <iostream>
    
    struct BigObject {
        int a{};
    };
    
    BigObject* createBigObj()
    {
        bool allGood = true ; // some real work here
    
        if ( allGood ) 
            return new BigObject{1};
        else 
            return nullptr;
    }
    
    void readBigObj(BigObject const * const bigOb)
    {
        if (bigOb)
            std::cout << bigOb->a << std::endl;
    }
    
    int main()
    {
        auto* big = createBigObj();
        readBigObj(big);
    
        return 0;
    }
    
    无法获取
    常量BigObject&
    ,因为该对象可以为null。函数没有更改指针的值或值,两者都应为
    const


    塔达!const value const pointor:)的原因

    C api没有引用。在LC++项目中使用LIBRUL或LIBTAR等LIBS,您应该知道如何使用指针。谢谢@ ThomasSablik。我不知道。有道理
    void readBigObj(BigObject const * const bigOb)