2016-11-12 87 views
0

我已經通過各種論壇帖子看過這裏和其他網站,但我還沒有看到任何涉及類似問題的內容。我遇到的問題是:除了數組元素爲6或以下時,studentInfo數組將不能正常運行。 我只是希望能夠有一個大小爲23數組,但是代碼返回:在類中使用數組時遇到問題(C++)

bash: line 12: 51068 Segmentation fault  $file.o $args 

我下面提供的代碼是我的實際代碼的簡化版本。我必須在我的程序中使用一個數組(因爲有些人可能會建議,所以沒有矢量),因爲它是我的任務的一部分。我對C++還是一個新的東西,所以任何答案的好解釋都會很棒。謝謝你的幫助!

#include <iostream> 
#include <string> 

using namespace std; 

class StudentGrades { 
    private: 
    string studentInfo[23]; 

    public: 
    void setStudentInfo(string info) { 
     for (int i = 0; i < 23; ++i) { 
      studentInfo[i] = info; 
     } 
    } 

    string getStudentInfo() { 
     for (int i = 0; i < 23; ++i) { 
      cout << studentInfo[i] << " "; 
     } 
    } 
}; 

int main() { 

    StudentGrades student1; 

    student1.setStudentInfo("Bob"); 

    student1.getStudentInfo(); 
} 
+1

它的簡化程度如何?一個問題是getStudentInfo不返回一個字符串。 –

回答

1

的代碼,因爲成員函數getStudentInfo返回任何雖然它與非void返回類型聲明是未定義行爲。

聲明它像

void getStudentInfo() const { 
    for (int i = 0; i < 23; ++i) { 
     cout << studentInfo[i] << " "; 
    } 
} 

而且這將是最好不要使用幻數。你可以像這樣在類中添加一個靜態常量數據成員

class StudentGrades { 
    private: 
    static const size_t N = 23; 
    string studentInfo[N]; 
    .... 

並在需要的地方使用它。例如

void getStudentInfo() const { 
    for (size_t i = 0; i < N; ++i) { 
     cout << studentInfo[i] << " "; 
    } 
}