2013-11-03 56 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) 
{}