2016-12-06 118 views
0

我想在我的構造函數裏初始化一個向量bool矢量。類構造函數初始化矢量向量

這是我的課:

class MyClass{ 
public: 
    MyClass(const OtherClass&g): 
     g(g), count(g.node_count(), std::vector<bool>(16))){} 


private: 
    const OtherClass&g; 
    std::vector<std::vector<bool>>count; 
}; 

但是當我嘗試初始化count我得到這個錯誤:

error: no match for call to ‘(std::vector<std::vector<bool> >) (int)’ 
+0

無關,[儘量避免](https://isocpp.org/blog/2012/11/on-vectorbool)'矢量',它是一個混合怪物。您可以使用['std :: bitset <>'](http://en.cppreference.com/w/cpp/utility/bitset)。 – vsoftco

+0

奇怪的爲什麼使用一個載體,如果你知道你需要16布爾?爲什麼'const OtherClass&'?使用此設計時遇到麻煩。當你將一個對象(A)引用給另一個對象(B)時,這個對象(A)應該屬於他(B),爲什麼'const'? (也許你不想修改他,所以沒關係) – Stargateur

回答

3

你想用fill constructor。如果你不使用C++ 11,你需要指定向量中元素的默認值。count(g.node_count(), std::vector<bool>(16, true))

0

首先,我想問你是否知道vector<bool>是一種特殊類型的向量,由於優化,這在某些情況下會導致一些不同的行爲。

如果你想使用它,你必須傳遞給構造函數vector<bool>(16, true)用16個真值填充它。