Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复杂层次结构中的统一初始化语法?_C++_Initialization_C++11 - Fatal编程技术网

C++ 复杂层次结构中的统一初始化语法?

C++ 复杂层次结构中的统一初始化语法?,c++,initialization,c++11,C++,Initialization,C++11,我使用的是GCC4.4.5 这是我问题的再现: #include <vector> class Test { public: Test( int a, int b = 42 ) : m_a( a ), m_b( b ) {} private: int m_a; int m_b; }; typedef std::vector<Test> TestList; class TestMaster { public: Test

我使用的是GCC4.4.5

这是我问题的再现:

#include <vector>

class Test
{
public:

    Test( int a, int b = 42 ) : m_a( a ), m_b( b ) {}

private:

    int m_a;
    int m_b;    
};

typedef std::vector<Test> TestList;


class TestMaster
{
public:

    TestMaster( TestList tests = TestList() ) : m_tests( tests ) {}


private:

    TestList m_tests;

};
但这并没有编译:

class TestManager : public TestMaster
{
public:

    TestManager()
        : TestMaster( { { 42, 54, 94 } } ) //?
    {}


};



int main()
{

    TestManager test_manager;


    return 0;
}
或者我只是没有使用正确的语法?还是GCC错了

错误:

g++ -std=c++0x hello_world.cpp
hello_world.cpp: In constructor \u2018TestManager::TestManager()\u2019:
hello_world.cpp:38: erreur: no matching function for call to \u2018TestMaster::TestMaster(<brace-enclosed initializer list>)\u2019
hello_world.cpp:24: note: candidats sont: TestMaster::TestMaster(TestList)
hello_world.cpp:21: note:                 TestMaster::TestMaster(const TestMaster&)
同样的错误


有什么想法吗?我不明白为什么语义在这里不起作用…

你有太多层次的构造在进行。初始值设定项列表仅在一个级别工作,因此您需要告诉它您希望列表应用于
TestMaster
TestList
参数:

TestMaster test_master(TestList({42,54,94}))
TestManager()
    : TestMaster( TestList( { 42, 54, 94 } ) )
{}
然后在
TestManager
的构造函数中使用相同的方法:

TestMaster test_master(TestList({42,54,94}))
TestManager()
    : TestMaster( TestList( { 42, 54, 94 } ) )
{}

正是我所想的。内部大括号将返回一个类似列表的对象,外部大括号将获取该对象,并将其解释为类似列表的对象类型的值的逗号分隔列表,但外部大括号内已经是一个对象。但是我的这篇小文章比上面的答案要混乱得多。所以我必须添加一个std::initializer\u list构造函数来允许我使用的语法?是的,如果
TestMaster
有一个
std::initializer\u list
构造函数,那么这可以用来初始化
m\u tests
成员。我认为这应该可以工作:
:TestMaster({42,54,94})
。即省略其中一个大括号。如果你不忽略它们,你得到的是一个试图初始化向量的
{{…}
。这将导致
{…}
尝试初始化
测试
(通过使用
向量
的初始值设定项列表构造函数)。但是
Test
没有三参数的ctor,因此这将失败。通过省略一个大括号级别,
{…}
初始化
向量将正常工作。