为什么可以在构造函数中修改const成员? [英] Why can const members be modified in a constructor?

查看:93
本文介绍了为什么可以在构造函数中修改const成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么可以在构造函数中修改const成员。

I'm curious why const members can be modified in the constructor.

初始化中是否有任何标准规则可以覆盖成员的 const-ness ?

Is there any standard rule in initialization that overrides the "const-ness" of a member?

struct Bar {
    const int b = 5; // default member initialization
    Bar(int c):b(c) {}
};

Bar *b = new Bar(2); // Problem: Bar::b is modified to 2
                     // was expecting it to be an error

有任何想法吗?

推荐答案

这不是修改(或分配),而是初始化。例如,

This is not modification (or assignment) but initialization. e.g.

struct Bar {
    const int b = 5; // initialization (via default member initializer)
    Bar(int c)
        :b(c)        // initialization (via member initializer list)
    {
        b = c;       // assignment; which is not allowed
    }
};

const 数据成员不能为

如果默认成员初始化程序和成员初始化程序都在同一个目录上提供,则可以(需要)通过成员初始化程序列表或默认成员初始化程序进行初始化。数据成员,默认成员初始化器将被忽略。这就是为什么 b-> b 初始化为值 2 的原因。

If both default member initializer and member initializer are provided on the same data member, the default member initializer will be ignored. That's why b->b is initialized with value 2.


如果成员具有默认成员初始化程序,并且该成员也出现在构造函数的成员初始化列表中,则默认成员初始化程序将被忽略。

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

另一方面,默认成员初始化器仅在成员初始化器列表中未指定数据成员时才生效。例如,

On the other hand, the default member initializer takes effect only when the data member is not specified in the member initializer list. e.g.

struct Bar {
    const int b = 5;   // default member initialization
    Bar(int c):b(c) {} // b is initialized with c
    Bar() {}           // b is initialized with 5
};

这篇关于为什么可以在构造函数中修改const成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆