代码之家  ›  专栏  ›  技术社区  ›  Fabio

在c中将指针赋给常数指针++

  •  0
  • Fabio  · 技术社区  · 2 年前

    我有一个常数指针 cp 这指向 A 和一个非常量指针 p 这指向 B . 我想说我可以分配 ,即。 p=cp 因为这样一来 内容提供商 p 指向 A. 我不能做相反的事情: cp=p 因为我是这样说的 内容提供商 应指向 B 但是 是一个常量指针,因此我无法更改它指向的内容。 我尝试了这个简单的代码,但结果是相反的,有人能解释我什么是正确的版本吗?

    std::vector<int> v;
    v.push_back(0);
    auto cp = v.cbegin(); // .cbegin() is constant 
    auto p = v.begin(); // .begin() is non constant 
    

    现在如果我写信 cp=p p=cp 编译器标记错误。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Marcus Müller    2 年前

    cbegin是指针 到恒定的东西 . 您可以将该指针更改为指向相同常量类型的对象。

    你把它和指针混淆了,指针是常数,指向的是非常数。

    const int* cp; // pointer to a constant value, but can point to something else
    int* const pc; // pointer is constant, value can change
    const int* const cpc; // pointer cannot be changed, value it points to cannot be changed
    

    const int value = 5; // can never change value
    const int value2 = 10; // can never change value
    const int* cp = &value; // our pointer to const int points at a const int
    *cp = 6; // error: the value of something const can't be changed
    cp = &value2; // fine, because we're pointing at a const int
    
    int* p const = &value; // error: trying to point a pointer to non-const to a const, which would allow us to:
    *p = 7; // which should be illegal.