Ich versuche, den folgenden Code auszuführen, aber es stürzt ab, sobald das Objekt der geerbten Klasse erstellt wird.Segmentierungsfehler C++ verursacht Absturz des Programms
Das Programm funktioniert bis zur Erstellung des geerbten Klassenobjekts, aber der Segmentierungsfehler tritt auf, nachdem die Zeile "Student * s" ausgeführt wurde.
Hier ist der Code:
#include <iostream>
#include <vector>
using namespace std;
class Person
{
protected:
string firstName;
string lastName;
int id;
public:
Person(string firstName, string lastName, int identification)
{
this->firstName = firstName;
this->lastName = lastName;
this->id = identification;
}
void printPerson()
{
cout << "Name: " << lastName << ", " << firstName << "\nID: " << id
<< "\n";
}
};
class Student: public Person
{
private:
vector<int> testScores;
public:
Student(string f, string l, int i, vector<int>& scores) :
Person(firstName, lastName, id)
{
this->firstName = f;
this->lastName = l;
this->id = i;
this->testScores = scores;
}
char calculate()
{
vector<int>::iterator it;
int sum = 0;
for (it = testScores.begin(); it != testScores.end(); it++)
{
sum += *it;
}
int avg = sum/(testScores.size());
if (avg >= 90 && avg <= 100)
return 'O';
else if (avg >= 80 && avg < 90)
return 'E';
else if (avg >= 70 && avg < 80)
return 'A';
else if (avg >= 55 && avg < 70)
return 'P';
else if (avg >= 40 && avg < 55)
return 'D';
else
return 'T';
}
};
int main()
{
string firstName;
string lastName;
int id;
int numScores;
cin >> firstName >> lastName >> id >> numScores;
vector<int> scores;
for (int i = 0; i < numScores; i++)
{
int tmpScore;
cin >> tmpScore;
scores.push_back(tmpScore);
}
cout << "Calling\n";
Student* s = new Student(firstName, lastName, id, scores);
cout << "Done\n";
s->printPerson();
cout << "Grade: " << s->calculate() << "\n";
return 0;
}
Ich bekomme nicht die 'Student (Zeichenfolge f, String l, int ich, Vektor & Scores): Person (Vorname, Nachname, ID)' Anweisung. Was möchten Sie erreichen, indem Sie die nicht initialisierten Datenelemente an den Basisklassenkonstruktor senden? –
'Student * s = neuer Student (firstName, lastName, id, scores);' scheint keine dynamische Zuweisung zu erfordern und es gibt kein passendes 'delete', um' Student' freizugeben. – user4581301