C++ 初始化构造函数中的结构向量
我不知道如何在构造函数中初始化struct的向量。有人能给我指点吗^^ 这是我的结构:C++ 初始化构造函数中的结构向量,c++,vector,constructor,struct,C++,Vector,Constructor,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>);
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);
};
类ShapeTwoD{
私人:
字符串名;
布尔空间;
向量顶点;
公众:
ShapeTwoD();
ShapeTwoD(字符串、布尔、向量);
虚拟字符串getName();
虚拟bool getContainsWarpSpace();
虚拟字符串toString();
矢量点;
虚拟双计算区域()=0;
虚拟布尔isPointInShape(int,int)=0;
虚拟布尔isPointonShape(int,int)=0;
虚拟空集合名(字符串);
虚拟虚拟虚拟空间(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::ShapeTwoD(){
name=“”;
containsWarpSpace=true;
顶点=”;
}
ShapeWod::ShapeWod(字符串名称、bool containsSwapSpace、向量顶点){
此->名称=名称;
此->containsSwapSpace=containsSwapSpace;
这->顶点=顶点;
}
它给了我这个错误:
ShapeTwoD.cpp:12:错误:与“((ShapeTwoD*)this)->ShapeTwoD::texts=”“”中的“operator=”不匹配
/usr/include/c++/4.4/bits/vector.tcc:156:注:候选项为:std::vector&std::vector::operator=(const std::vector&)[带_Tp=Point,_Alloc=std::allocator]
根据要求:错误消息表示没有对
顶点=“
的定义。但是,向量已经存在(且为空),因此不得初始化。将空字符串附加到向量可以通过
顶点来完成代码>如有必要看起来您正试图将向量初始化为空
编译器将为您创建一个空向量,因此您不需要这样做
ShapeWod实例中的数字和布尔值应该初始化为合理的默认值,就像containsSwapSec
变量一样
ShapeTwoD::ShapeTwoD()
containsWarpSpace = true;
}
您可以改为使用初始值设定项列表。对于这个例子来说这并不重要,但是如果您的对象是非平凡类型,这是一个很好的实践
// Preferred: use initializer list.
ShapeTwoD::ShapeTwoD()
: containsWarpSpace(true)
{}
请读一本教科书。谢谢。请测试您自己的代码,并仅在发现实际问题时询问-上一个.cpp文件中的注释表明您尚未尝试运行它。您在构造函数中初始化内容的方式已被破坏。读你的书,它会解释为什么。@UnholySheep我只能想到把顶点=”
和=0
。与错误所述的错误相同,您不能使用未定义的顶点=“
”。你这样做到底想达到什么目的?向量本身已经存在(并且为空),如果要添加单个元素,请尝试使用顶点代码>将向向量添加一个空字符串元素