我對Qt和C++很陌生,但對編程根本不陌生。我在我的程序中使用指針時遇到問題。在我的頭文件我有以下私有變量的指針賦值:嘗試在Qt中接收指針值時出現分段錯誤
private:
QString *currentFile;
在我的節目,我已經得到了由currentFile指針的值複製到另一個QString的可變啓動功能:
QString fileName = *currentFile;
然而這在調試時會立即給我分段錯誤。我完全不知道我做錯了什麼。
該程序運行得很好,直到我調用函數試圖獲得指針的線索。我想這可能是監守指針是空的,所以我嘗試添加以下代碼到我的建築工:
*currentFile = QString::null;
要將null
值賦給指針值,然而,這只是儘快給我的分段錯誤的constructer被調用。
希望有人能幫忙。
由於
EDIT
更多的代碼:
notepad.h:
class Notepad : public QMainWindow
{
Q_OBJECT
public:
Notepad();
private slots:
void open();
void save();
void saveAs();
void quit();
private:
QTextEdit *textEdit;
QString *currentFile;
QString *currentContents;
};
函數產生錯誤(無效保存())在記事本中。 cpp:
void Notepad::save(){
QString fileName = *currentFile;
if(fileName != "")
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly))
{
QMessageBox::critical(this, tr("Error"), tr("Could not write to file"));
return;
}
else
{
QTextStream stream(&file);
QString editorContent = textEdit->toPlainText();
currentContents = &editorContent;
stream << editorContent;
stream.flush();
file.close();
}
}
else
saveAs();
}
更多的代碼。另外,不要使用指針,你不需要它。 –
在構造函數中增加了更多代碼.. – Simon
'* currentFile = QString :: null'將一個未初始化的指針解引用。如果有的話,這應該是'currentFile = QString :: null'。 – eran