小编Jer*_*Lee的帖子

在类和构造函数中使用向量时出现分段错误

我正在编写一个编程项目列表,而这个项目是制作15个拼图(幻灯片拼图)的。当我遇到一个小障碍时,我正在从事该项目。

我的代码编译得很好,但是当我运行它时,在第12行出现了分段错误: pos[0] = x;

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Tile{
private:
    vector<int> pos;
    int value;
public:
    Tile(int x, int y, int value_){
        pos[0] = x;
        pos[1] = y;
        value = value_;
    }
    ~Tile(){}
    int getPos(int a){return pos[a];}
    void setPos(int a, int b){pos[a] = b;}
};
int main(){
    Tile tile1(1, 2, 10);
    Tile* t1;
    t1 = &tile1;

    // returns position "x"
    cout << t1->getPos(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的意思是,我可以不必使用向量/数组来处理整个项目就可以完成整个项目,但是我仍然想知道,就我自己的理解而言,这为什么行不通。

基于我运行的调试,程序在初始化pos []向量的值时遇到了麻烦。

另一个问题:可能与此有关,我尝试在实例化矢量时设置其大小。

vector<int> pos(2); …

c++ pointers vector segmentation-fault

7
推荐指数
2
解决办法
91
查看次数

标签 统计

c++ ×1

pointers ×1

segmentation-fault ×1

vector ×1