gpt4 book ai didi

c++ - const 成员可以在 c++ 构造函数中初始化吗?

转载 作者:行者123 更新时间:2023-11-30 03:26:49 26 4
gpt4 key购买 nike

我阅读了代码片段 here .请搜索“Const 类数据成员”以转到该部分。代码如下:

class Test
{
const int i;
public:
Test (int x)
{
i=x;
}
};

int main()
{
Test t(10);
Test s(20);
}

我使用 VS2013 警告我它不正确。据我所知,const 成员变量只能通过初始化列表进行初始化。 ……喜欢:

Test (int x):i(x){}

较新的 C++ 标准更新是否支持该功能(如果是这样,更改听起来很合理,在函数体中初始化似乎没有区别,对吧?)?或者文件出错(我估计不会出错)。

最佳答案

规则没有改变(从 C++98 开始)。

注意i=x;在构造函数体内不是初始化而是赋值;它们是不同的东西。对于 const 成员,它们只能是 initialized ,

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

例如测试 (int x):i(x){},

但是不能赋值,

Test (int x)
{
i=x; // assignment is not allowed
...
i=42; // assignment again; that makes no sense for const at all
}

关于c++ - const 成员可以在 c++ 构造函数中初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47977221/

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