【问题标题】:Why is const MyClass const* not valid?为什么 const MyClass const* 无效?
【发布时间】:2014-01-02 14:18:13
【问题描述】:

我是 C++ 的新手,在尝试阅读此类原型时会感到困惑。

这个原型在 Visual Studio 2012“构建”(在 Native C++ 静态库中,而不是 C++/CLI),虽然它没有不要使指针保持不变。 我注意到它会抛出一个警告,我一开始没有看到。

C++ Visual Studio 2012

     int intTest =3;
     int intTest2 = 5;
     const int const* pointerTest = &intTest;
     pointerTest = &intTest2; //This works

     const int* const pointerTest2 = &intTest;
     pointerTest2 = &intTest2; //This doesn't build because the pointer is constant.

我意识到我的错误是因为当我尝试在 Linux(Eclipse with GCC 4.6.3)中构建这段代码时,它会抛出一个错误:

重复的“常量”

我错误地写了这个而不是 const MyClass* const,但我没有注意到它,因为 Visual Studio 没有抛出错误。

为什么这个语法是错误的?我不是故意写的,但我想了解。

【问题讨论】:

标签: c++ visual-studio-2012


【解决方案1】:

const 将术语装饰在其左侧,除非它位于最左侧,否则将其装饰在其右侧。

使用上述规则重写您的声明

int const const* pointerTest = &intTest;

你应该写:

const int * const pointerTest = &intTest;

或者坚持 right-const 风格就不会迷惑了:

int const * const * const * const someEvilVariable = foo();

【讨论】:

  • 所以从“int const const* pointerTest = &intTest;”这意味着我写道:“[int const const]* pointerTest = &intTest;”指向“int const const”的指针?现在这是有道理的!不过希望 Visual Studio 会像 GCC 一样抛出错误。
【解决方案2】:

在此声明中

 const int const* pointerTest = &intTest;

限定符 const 只是重复了。相当于

 const int * pointerTest = &intTest;

 int const* pointerTest = &intTest;

这里定义了一个常量数据的指针。指针本身不是常量。

在此声明中

const int* const pointerTest2 = &intTest;

您将指针本身定义为常量。只能在定义时初始化,不可更改。

【讨论】:

    【解决方案3】:

    const MyClass *MyClass const * 都声明了一个指向 const 数据的指针,因此 MyClass 两侧的 consts 都在做完全相同的事情,因此会发出警告。

    理解声明内容的一种方法是从右到左阅读声明,例如

    MyClass const * const pointerTest = &intTest; //a const pointer to const data of type MyClass
    

    但是,您可以将限定符放在类名旁边的任一侧,如下所示:

    const MyClass * const pointerTest = &intTest; //a const pointer to data that is const.
    

    其他可能的声明:

    const MyClass * pointerTest = &intTest; //a non-const pointer to const data.
    MyClass * const pointerTest = &intTest; //a const pointer to non-const data.
    

    【讨论】:

      【解决方案4】:

      const 出现在 type (int) 之前或之后都没有关系。

      因此

      const int const* pointerTest
      

      翻译成

      const int* pointerTest
      

      因为把const 放了两次什么都没做。

      重要的是const* 的顺序,所以在你的情况下:

      -第一个是pointerconst int

      const int const* pointerTest = &intTest;
      

      -第二个是const pointerconst int:(因为const* 之后)

      const int* const pointerTest2 = &intTest;
      

      因此您不能更改指针并得到错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-05
        • 1970-01-01
        • 2016-07-14
        • 2019-06-26
        • 2010-11-11
        相关资源
        最近更新 更多