【问题标题】:Segmentation fault with accessor function访问函数的分段错误
【发布时间】:2013-11-18 12:35:15
【问题描述】:

我正在练习 C++,并创建了一个类,用于存储从快速格式读取的序列及其名称。代码如下:

#include<fstream>
#include<iostream>
#include<string>
#include<vector>

using namespace std;

class Sequence {
    vector<string> fullSequence, sequenceNames;

public:
    void fastaRead(string fileName);
    string getSequence(int index);

};

string Sequence::getSequence(int index)
{
    return fullSequence[index];
}


void Sequence::fastaRead(string fileName)
{
    vector<string> fullSequence, sequenceNames;
    ifstream inputFile;
    inputFile.open(fileName);
    if (inputFile.is_open()) {
        string currentSeq;
        string line;
        bool newseq = false;
        while (getline(inputFile, line))
        {
            if (line[0] == '>') {
                sequenceNames.push_back(line.substr(1,line.size()));
                newseq = true;
            } else {
                if (newseq == true) {
                    fullSequence.push_back(currentSeq);
                    currentSeq = line;
                    newseq = false;
                } else {
                    currentSeq.append(line);
                }
            }
        }
    }
    inputFile.close();
}


int main()
{
    Sequence inseq;
    cout << "Fasta Sequence Filepath" << endl;
    string input;
    getline(cin, input);
    inseq.fastaRead(input);
    inseq.getSequence(0);
    return 0;
}

但是,当我使用以下虚拟输入文件运行程序时:

>FirstSeq
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
>SecondSeq
TTTTTTTTTTTTTT
>ThirdSequence
CCCCCCCCCCCCCC
>FourthSequence
GGGGGGGGGGGGGG

当调用inset.getSequence(0) 行时出现分段错误。我做了什么导致段错误,我如何确保它不会发生?我知道这可能与指针中的错误有关,但我认为我没有使用过指针,如果我没记错的话需要 * 字符。

谢谢, 本。

【问题讨论】:

    标签: c++ class segmentation-fault accessor


    【解决方案1】:

    您需要在 void Sequence::fastaRead 函数中删除 vector&lt;string&gt; fullSequence, sequenceNames;。当您在该函数中定义这些变量并使用它们时,您不会访问类中具有相同名称的变量,而是访问您在该函数中定义的局部变量,除非您在它们前面加上 this-&gt; 而访问。

    类中的变量实际上是空的,你得到一个分段错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 2016-02-26
      • 2023-03-03
      • 2020-05-14
      相关资源
      最近更新 更多