c++ - 插入数据时出现段错误

标签 c++ vector

我目前正在尝试在一个方法中插入数据,然后将其添加到 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);
    }
}

setNamesetContainsWarpSpace 是普通的设置方法。

编辑
好的,我刚刚找到导致段错误的行。 这是我的 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/

相关文章:

java - 在netbeans中从mysql数据库绑定(bind)jtable

haskell - 如何变异 STVector?

c++ - set <T> vs set <T, comparator> (C++ 多态性)

c++ - enum 类型不能接受 cin 命令

c++ - 可移植字符换行符

c++ - 使用 C++ 获取设备列表

header 或源代码中的 C++ 函数修饰符?快速引用

c++ - c++和opencv中 vector 下标超出范围错误

c - 我可以使用哪种索引方法来存储数组中 X^2 vector 之间的距离而没有冗余?

r - 按 r 中的月份名称对向量进行排序