首页 > 解决方案 > C++ 中的常量成员是什么?

问题描述

class Foo
{
public:
    const int a;
    const int* x;
    int* const y;
    Foo() : a{ 0 }, y{ new int(20) } {
        x = new int(10);
    }
};

int main()
{
    Foo f;
    // f.a = 100; // cannot
    f.x = new int(100);
    // f.y = new int(100); // cannot

}

const int a被定义为类的字段时,它被称为常量成员。它必须在初始化器列表中初始化,之后不能更改。

const int* x(与 相同int const* x)和怎么int* const y样?哪一个应该被称为常量成员?如果“常量成员”被定义为必须在初始化列表中初始化并且之后不能更改的字段,则常量成员是y而不是x。我在这里错了吗?

编辑

根据 IntelliSense,y是一个常量成员。

在此处输入图像描述

好的。我确信我没有错。我会尽快删除这个问题。感谢您的参与!

标签: c++

解决方案


“const int* x”是指向 const int 的(非 const)指针。由于 x 是非常量的,因此不需要在构造时对其进行初始化。

这里有些例子:

class C
{
public:
    C() :
      const_int(1),
      const_int_again(2),
      const_ptr_to_non_const_int(nullptr),
      const_ptr_to_const_int(nullptr)
    {}

private:
    const int const_int;
    int const const_int_again;
    
    const int* ptr_to_const_int; // Doesn't need initialized
    int const* ptr_to_const_int_again; // Doesn't need initialized

    int* const const_ptr_to_non_const_int;
    const int* const const_ptr_to_const_int;
    int const* const const_ptr_to_const_int_again;
};

您可能会发现cdecl.org网站很有帮助。


推荐阅读