2011-03-03 76 views
4

我正在使用GCC 4.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; 

}; 

现在,这个工程:

int main() 
{ 

    TestList test_list = { 15, 22, 38 }; 


    return 0; 
} 

但是,这并不编译:

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 test_master = { { 42, 54, 94 } }; 

与同errror。

有什么想法?我看不出为什么语义在这里不起作用...

回答

4

你有太多的建设水平正在进行。初始化列表只在一个级别上工作,所以你需要告诉它你想要的清单应用到TestList参数TestMaster

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

然后在TestManager构造相同:

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

正是我的想法。内括号会返回一个类似列表的对象,而外括号会带上这个对象,并让它被解释为逗号分隔的列表类对象类型的值列表,但是外括号内的内容是已经是一个对象。但是我的这个小文本比上面':s'的回答更令人困惑。 – rubenvb 2011-03-03 14:23:43

+0

所以我将不得不添加一个std :: intializer_list <>构造函数来允许我使用的语法? – Klaim 2011-03-03 14:34:00

+0

是的,如果'TestMaster'有一个'std :: initializer_list'构造函数,那么这可以用来初始化'm_tests'成员。 – 2011-03-03 16:39:27