简体   繁体   English

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

[英]Can const member be initialized in c++ construtor?

I read code snippet here . 在这里阅读代码片段。 Please search "Const class Data members" to get to the section. 请搜索“常量类数据成员”以转到此部分。 Code is like below: 代码如下:

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

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

I use VS2013 warning me it's not correct. 我使用VS2013警告我这是不正确的。 As I know, const member variables can only be initialized by an initializing list. 据我所知,const成员变量只能通过初始化列表进行初始化。 Sth. STH。 like: 喜欢:

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

Did the newer C++ standard update to support that(If so, the change sounds reasonable, initializing in function body seems no difference, right?)? 较新的C ++标准是否进行了更新以支持该标准(如果这样,更改听起来很合理,在函数体中初始化似乎没有区别,对吗?)? Or the document make a mistake(I presume it won't make such mistake). 或文档出错(我想不会出错)。

The rule didn't change (from C++98). 规则没有改变(从C ++ 98开始)。

Note that i=x; 注意, i=x; inside the constructor's body is not initialization but assignment; 构造函数内部不是初始化而是赋值; they are different things. 他们是不同的东西。 For const members, they can only be initialized , 对于const成员,只能将它们初始化

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. 对于无法默认初始化的成员(例如引用成员和const限定类型的成员),必须指定成员初始化程序。

eg Test (int x):i(x){} , 例如Test (int x):i(x){}

but they cannot be assigned, 但无法分配,

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

Yes, const members can only be initialized (by using an initialization list) and not assigned to, as is shown in your code snippet. 是的,如代码片段所示,只能对const成员进行初始化(通过使用初始化列表),而不能将其分配给const成员。 No, newer C++ standards have not updated this to support assignment in the constructor. 否,较新的C ++标准尚未对此进行更新以支持构造函数中的赋值。

The tutorial in question that contains that code snippet is wrong. 包含该代码段的相关教程是错误的。 I'd advise against reading such tutorials as they more often than not have subtle (and not-so-subtle) errors in them. 我建议您不要阅读此类教程,因为它们经常会出现细微(或不太细微)的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM