gpt4 book ai didi

c++ - 段错误c++导致程序崩溃

转载 作者:行者123 更新时间:2023-11-28 05:38:49 25 4
gpt4 key购买 nike

我正在尝试运行以下代码,但它在创建继承类的对象后立即崩溃。

程序在创建继承类对象之前工作正常,但在执行“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;
}

最佳答案

    Student(string f, string l, int i, vector<int>& scores) :
Person(firstName, lastName, id)

使用 Person 自己的 firstNamelastNameid 成员来构造 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;
}

还可以再改进一下。 testScores 可以用 the member initializer list 初始化.这允许 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 发现的被零除错误。

关于c++ - 段错误c++导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37623714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com