我目前正在尝试在一个方法中插入数据,然后将其添加到 vector 中。出于某种原因,当我到达输入第二组 x y 的点时,我总是遇到段错误。
我认为这是导致故障的部分:
if (shape == "square") {
for (int i = 0; i < 4; i++) {
cout << "Please enter x-coordinate of pt." << i+1 << " : ";
cin >> x;
cout << "Please enter y-coordinate of pt." << i+1 << " : ";
cin >> y;
sq->setName(shape);
sq->setContainsWarpSpace(type);
sq->setVertices(i,x,y);
shapes.push_back(sq);
}
}
setName
和setContainsWarpSpace
是普通的设置方法。
编辑
好的,我刚刚找到导致段错误的行。
这是我的 setName
方法
void ShapeTwoD::setName(string name) {
this->name = name;
}
EDIT2
根据要求,这是名称和形状的定义。是的,sq 是 Square
类的指针。
内部驱动类:
string shape;
内部 ShapeTwoD 类:
class ShapeTwoD {
private:
string name;
bool containsWarpSpace;
double area;
};
知道为什么这会导致错误吗?
最佳答案
是否有可能是 sq 指针未初始化,因为这似乎是问题所在。 如果我编写并执行以下内容:
#include <string>
#include <iostream>
using namespace std;
class A
{
private:
string name;
public:
void SetName(string name)
{
this->name = name;
cout<<this->name<<endl;
}
};
int main()
{
A* obj = new A();
obj->SetName("test");
return 0;
}
代码编译和执行完美。但是,如果我更改行:
A* obj = new A();
与:
A* obj = NULL;
然后我得到一个 SEGFAULT。
关于c++ - 插入数据时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795898/