【问题标题】:What are constant members in C++?C++ 中的常量成员是什么?
【发布时间】:2021-04-12 21:13:40
【问题描述】:
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 是一个常量成员。

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

【问题讨论】:

  • @reece 请不要尝试用 cmets 回答问题。它可以防止人们对不正确的信息投反对票。
  • 你没有错。 int* const y 声明一个常量指针
  • 我其实是想反击下面的post
  • 半相关:Handy tool
  • @MoneySetsYouFree:评论有误。可以修改指向 const 数据的指针。不能修改 const 指针。

标签: c++


【解决方案1】:

“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 网站很有帮助。

【讨论】:

  • 因为这是一个 c++ 问题 - 也可以添加引用 - 或链接到其他好的答案之一(例如,请参阅此问题 stackoverflow.com/questions/2627166/…
  • 还有一个 T * const * const 与一个 T const * *
猜你喜欢
  • 2011-10-15
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多