简体   繁体   English

C++ 构造函数初始化列表“错误:预期的'('或'{'”

[英]C++ constructor initializer list “ error: expected '(' or '{'”

This doesn't compile:这不编译:

class foo
{
  struct node
  {
    wchar_t val;
    unordered_map<wchar_t,unique_ptr<node>> children;
  };

  node root;

public:

  foo() : 
    root.val(L'า'), // error: expected '(' or '}'
    root.children(unordered_map<wchar_t, unique_ptr<node>>())
    {}; // error: expected '(' or '}'
};

But this does:但这确实:

class foo
{
...<same as above> ....

    foo() : root{L'า', unordered_map<wchar_t, unique_ptr<node>>()}{};
};

Please enlighten me, why I can't express as in the former?请赐教,为什么我不能像前者那样表达? I looked for over an hour and couldn't find the explanation.我找了一个多小时,找不到解释。 I'm sure I've overlooked something simple.我确定我忽略了一些简单的事情。

clang version 9.0.0 (tags/RELEASE_900/final) Target: x86_64-apple-darwin17.7.0 clang++ -std=c++17 clang 版本 9.0.0 (tags/RELEASE_900/final) 目标:x86_64-apple-darwin17.7.0 clang++ -std=c++17

Thank you!谢谢!

Because you just can't.因为你就是做不到。

A constructor's member-initialiser is for initialising, well, members.构造函数的成员初始化器用于初始化成员。 Not selected members of members.未选择成员的成员。 It's a simple as that.就这么简单。 There is just no feature to do what you want.没有功能可以做你想做的事。

Could the C++ standard provide such a thing? C++ 标准能提供这样的东西吗? Possibly.可能。 But in general it would open up all sorts of nasty edge cases with half-initialised objects, unclear semantics, and exception safety nightmares.但总的来说,它会打开各种令人讨厌的边缘情况,包括半初始化对象、不明确的语义和异常安全噩梦。 (What would happen to the rest of the root object, if more existed? How would the object itself be initialised? In part? In full? When?) (如果存在更多, root object 的 rest 会发生什么情况?如何初始化 object 本身?部分?全部?什么时候?)

All for absolutely no gain whatsoever.一切都是为了绝对没有任何收获。

Transitively invoking constructors keeps initialisation simple, clear, and always "owned" by the appropriate object in the code.传递调用构造函数使初始化保持简单、清晰,并且始终由代码中相应的 object“拥有”。

Use the member's own initialisation features, exactly as you are in your second example.使用成员自己的初始化功能,就像您在第二个示例中一样。

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

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