【发布时间】:2017-02-03 01:12:59
【问题描述】:
我正在尝试使用以下连接更改某些标签的文本:
connect(ui->styleSelector, SIGNAL(currentIndexChanged(int)), this, SLOT(setStyle(int)));
connect(this, SIGNAL(instrumentChanged(QString)), ui->label_inst_1, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_2(QString)), ui->label_inst_2, SLOT(setText(QString)));
connect(this, SIGNAL(instrumentChanged_3(QString)), ui->label_inst_3, SLOT(setText(QString)));
我的setStyle 槽:
void SamplerModule::setStyle(int style){
m_style = style;
emit instrumentChanged(m_instruments[m_style][0]);
emit instrumentChanged_2(m_instruments[m_style][1]);
emit instrumentChanged_3(m_instruments[m_style][3]);
}
还有我的数组(在我的 Class 构造函数中设置)
QString m_instruments[3][3];
m_instruments[0][1] = "Trompette";
m_instruments[0][2] = "Basse";
m_instruments[0][3] = "Piano";
m_instruments[1][1] = "Guitare";
m_instruments[1][2] = "Batterie";
m_instruments[1][3] = "Basse";
m_instruments[2][1] = "Basse";
m_instruments[2][2] = "Batterie";
m_instruments[2][3] = "Guitare";
但是当我尝试运行代码时,由于我的信号使用m_instruments[x][0],我遇到了分段错误。
我真的不明白为什么。我的插槽setStyle 有权访问这个数组,为什么会出现这个分段错误?
详情:
如果我在标题中设置QString m_instruments[3][3]; 而不是QString m_instruments[][3];,那么段错误就会消失。 但是,数组在构造函数之外是空的。
qDebug() << m_instruments[0][0]; 在构造函数中返回“Trompette”,但在我的setStyle 插槽中返回“”!
【问题讨论】:
-
你知道数组是0索引的,对吧?因此,大小为 3 的数组将包含索引为 0,1 和 2 的元素。访问此类数组中索引为 3 的元素是错误的。
-
我的错,我尝试了很多次来编辑我忘记设置正确索引的所有内容。它已修复,但分段错误仍然存在。 ://
-
什么值作为参数传递给 setStyle() 槽?如果它不是 0、1 或 2,那么您将访问 m_instruments 数组中的无效索引。
-
你能像你的代码那样取悦构造函数的完整主体吗?具体来说,它实际上是否包含
QString m_instruments[3][3];位? (实际上是隐藏成员变量)? -
对不起,问题还是一样。我刚刚添加了更多信息。
标签: c++ qt segmentation-fault