我正在尝试运行以下代码,但只要创建了继承类的对象就会崩溃。
程序正常工作,直到创建继承的类对象,但在" Student * s"之后发生了分段错误。行被执行。
以下是代码:
#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;
}
答案 0 :(得分:1)
Student(string f, string l, int i, vector<int>& scores) :
Person(firstName, lastName, id)
使用Person
自己的firstName
,lastName
和id
成员来构建Person
。这可能会或可能不会出现分段错误和繁荣,但肯定会进入未定义的行为。
OP想要更像这样的东西,而不是使用传递的参数:
Student(string f, string l, int i, vector<int>& scores) :
Person(f, l, i)
{
// all of the members that were set here don't need to be set.
// Person did it already
this->testScores = scores;
}
可以进一步改进。可以使用the member initializer list初始化testScores
。这允许scores
立即填入testScores
,编译器可以进行各种有趣的优化。
Student(string f, string l, int i, vector<int>& scores) :
Person(f, l, i), testScores(scores)
{
}
尽可能初始化初始化列表中的成员变量。 `人也可以改进:
Person(string first, string last, int identification):
firstName(first),
lastName(last),
id(identification)
{
}
现在可以找到并修复Rakete1111发现的零除虫病。