c++ - 为什么 const 成员可以初始化两次?

标签 c++ c++11 initialization constants initializer-list

下面是一段代码片段,可以在 vs2015 中编译运行而不会出错

#include<iostream>
using namespace std;

class A {
    public:
        A(int b) :k(b) {}//second time
    const int k = 666;//first time
};

int main() {
    A a(555);
    cout << a.k << endl;
    return 0;
}

输出为 555。但据我所知,const 对象应该只初始化一次,之后该值是不可修改的。

最佳答案

它没有被初始化两次; default member initializer只是被忽略了。所以对于A a(555);a.k被初始化为555

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.

根据标准,[class.base.init]/10 :

If a given non-static data member has both a default member initializer and a mem-initializer, the initialization specified by the mem-initializer is performed, and the non-static data member's default member initializer is ignored. [ Example: Given

struct A {
  int i = /* some integer expression with side effects */ ;
  A(int arg) : i(arg) { }
  // ...
};

the A(int) constructor will simply initialize i to the value of arg, and the side effects in i's default member initializer will not take place. — end example ]

另一方面,给定

class A {
public:
    A() {}            // k will be initialized via default member initializer, i.e. 666
    A(int b) :k(b) {} // k will be initialized via member initializer list, i.e. b

    const int k = 666;
};

那么对于A a;a.k会被初始化为666

关于c++ - 为什么 const 成员可以初始化两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152696/

相关文章:

c++ - 在对象中存储引用会产生奇怪的结果

c++ - 通过 C++ 中的函数返回数组

c++ - 这两个说法在N4140中不是不兼容吗?

c++ - 为什么我无法将 std::make_unique<S> 作为函数参数传递?

c++ - 如何检测可变参数模板中的第一个和最后一个参数?

java - 如何处理 java.rmi.UnknownHostException

c# - 'statically linked' 和 'dynamically linked' 是什么意思?

c++ - 来自点列表的最佳路径c++

Swift enum - 约束关联值

c# - 静态变量初始化