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。
有什麼想法?我看不出爲什麼語義在這裏不起作用...
正是我的想法。內括號會返回一個類似列表的對象,而外括號會帶上這個對象,並讓它被解釋爲逗號分隔的列表類對象類型的值列表,但是外括號內的內容是已經是一個對象。但是我的這個小文本比上面':s'的回答更令人困惑。 – rubenvb 2011-03-03 14:23:43
所以我將不得不添加一個std :: intializer_list <>構造函數來允許我使用的語法? – Klaim 2011-03-03 14:34:00
是的,如果'TestMaster'有一個'std :: initializer_list'構造函數,那麼這可以用來初始化'm_tests'成員。 – 2011-03-03 16:39:27