Skip to main content
 首页 » 编程设计

c++之在类和构造函数中使用 vector 时出现段错误

2025年12月25日42lvdongjie

我在做一个编程项目的 list ,而这个项目是做一个15拼图(slide拼图)。当我遇到一个小障碍时,我正在研究这个项目。

我的代码编译得很好,但是当我运行它时,我在第 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; 
} 

我的意思是,我可以完成整个项目而不必使用 vector/数组来处理位置,但我仍然想知道,为了我将来的理解,为什么这不起作用。

根据我运行的调试,程序在初始化 pos[] vector 的值时遇到问题。

另一个问题:可能相关,我尝试在实例化 vector 时设置 vector 的大小。
vector<int> pos(2);
但是后来我得到了调试错误:
error: expected identifier before numeric constant
不知道这里发生了什么。我尝试了很多不同的东西,但我似乎无法弄清楚为什么我的 vector 在类中不起作用。

我确信有一百种方法可以让我把这个小作品做得更好,我很想知道你是如何修复它的,但我也需要知道什么是错的,特别是在我写的内容的背景下并尝试过。

谢谢。

请您参考如下方法:

I tried setting the size of the vector when it was instantiated.

vector<int> pos(2); 

But then I get the debug error:

error: expected identifier before numeric constant 


那是编译错误,而不是调试错误。

你不能像那样初始化成员。但是,您可以(并且应该)使用父构造函数初始化它们:
Tile(int x, int y, int value_) 
    : pos(2) 
{ 
    pos[0] = x; 
    pos[1] = y; 
    value = value_; 
} 

目前,您只是将 vector 留空,然后访问(并写入!)不存在的元素。

无论如何,你真的不想要一个 vector :那是很多动态分配。一个漂亮的数组怎么样?或者只是两个 int s。