首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中的常量成员是什么?

问C++中的常量成员是什么?
EN

Stack Overflow用户
提问于 2021-04-13 05:13:41
回答 1查看 127关注 0票数 0
代码语言:javascript
复制
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是一个常量成员。

​

​

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-13 05:49:23

"const int* x“是一个指向const int的(非常量)指针。因为x是非常数,所以它不需要在构造时初始化。

下面是一些示例:

代码语言:javascript
复制
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网站很有帮助。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67065762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档