2013-11-03 60 views
-2

我不知道如何在構造函數中初始化struct向量。任何人都可以給我指針? ^^在構造函數中初始化struct的向量

這是我的結構:

struct Point { 
int x; 
int y; 
}; 

這是我的頭文件:

class ShapeTwoD { 
private: 
string name; 
bool containsWarpSpace; 
vector<Point> vertices; 
public:  
ShapeTwoD(); 
ShapeTwoD(string,bool,vector<Point>); 

virtual string getName(); 
virtual bool getContainsWarpSpace(); 
virtual string toString(); 

vector<Point> points; 

virtual double computeArea() = 0; 
virtual bool isPointInShape(int,int) = 0; 
virtual bool isPointonShape(int,int) = 0; 

virtual void setName(string); 
virtual void setContainsWarpSpace(bool); 
}; 

這是我的.cpp文件:

ShapeTwoD::ShapeTwoD() { 
name = ""; 
containsWarpSpace = true; 
vertices = ""; 
} 

ShapeTwoD::ShapeTwoD(string name, bool containsWarpSpace,vector<Point>vertices) { 
this->name = name; 
this->containsWarpSpace = containsWarpSpace; 
this->vertices = vertices; 
} 

它給了我這個錯誤:

ShapeTwoD.cpp:12: error: no match for ‘operator=’ in ‘((ShapeTwoD*)this)->ShapeTwoD::vertices = ""’ /usr/include/c++/4.4/bits/vector.tcc:156: note: candidates are: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = Point, _Alloc = std::allocator]

+0

請閱讀教科書。謝謝。 – Abyx

+0

請測試您自己的代碼,並詢問是否發現實際問題 - 最後一個.cpp文件中的註釋表明您還沒有嘗試過運行它。 – UnholySheep

+0

您在構造函數中初始化事物的方式已中斷。閱讀你的書,它會解釋爲什麼。 – Griwes

回答

2

根據要求:
錯誤消息指出vertices = ""沒有定義。但是矢量已經存在(並且是空的),因此不能被初始化。
如果需要,可以通過vertices.push_back("");將一個空字符串添加到矢量

0

它看起來像你試圖初始化矢量爲空。

編譯器會爲你創建一個空向量,所以你不需要。

ShapeTwoD實例中的數字和布爾值應該被初始化爲合理的默認值,與變量一樣。

ShapeTwoD::ShapeTwoD() 
    containsWarpSpace = true; 
} 

您可以改爲使用初始化列表。這個例子並不重要,但是如果你的對象是非平凡的類型,這是一個很好的習慣。

// Preferred: use initializer list. 
ShapeTwoD::ShapeTwoD() 
: containsWarpSpace(true) 
{}