2016-11-12 53 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] << " "; 
    } 
}