gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:30:42 31 4
gpt4 key购买 nike

下面是一段代码片段,可以在 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com