gpt4 book ai didi

c++ - 初学者 C++ 继承

转载 作者:行者123 更新时间:2023-11-30 01:44:10 25 4
gpt4 key购买 nike

我对 C 的经验很少,但对 OOP 的经验为零,我正在尝试解决 C++ 中有关继承的 HackerRank 问题。我想我搞砸了应该如何定义派生类的某个地方,因为我的 average 变量计算不正确。此外,我什至不确定如何打印测试用例进行调试,因为当我将 cout 语句添加到 calculate() 时,它什么也没做。

#include <iostream>
#include <vector>

using namespace std;

// given this definition
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";
}

};

// this is what I'm supposed to be creating
class Student : public Person{
private:
vector<int> testScores;
public:
Student(string firstName, string lastName, int id, vector<int> testScores) : Person(firstName,lastName, id)
{};

char calculate(){
double average = 0;
for (int i = 0; i < testScores.size(); i++){
average += testScores[i];
cout << average;
}
average = average / testScores.size();
if ((average >= 90) && (average <= 100))
return 'O';
else if ((average >= 80) && (average < 90))
return 'E';
else if ((average >= 70) && (average < 80))
return 'A';
else if ((average >= 55) && (average < 70))
return 'P';
else if ((average >= 40) && (average < 55))
return 'D';
else if (average < 40)
return 'T';
else
return 'X'; // always returns this??
}

};

// also given this main
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);
}
Student* s = new Student(firstName, lastName, id, scores);
s->printPerson();
cout << "Grade: " << s->calculate() << "\n";

return 0;
}

最佳答案

问题是您将从控制台读取的分数提供给构造函数:

 Student* s = new Student(firstName, lastName, id, scores);

不幸的是,在您的类(class)中,您没有使用它来初始化 Student 对象的分数:

Student(string firstName, string lastName, int id, vector<int> testScores)
: Person(firstName,lastName, id)
{}; // ouch testScores is lost

只需像这样 ccopy 构建你的学生 vector :

Student(string firstName, string lastName, int id, vector<int> testScores)
: Person(firstName,lastName, id), testScores(testScores)
{};

其他与您的问题无关的备注

如果您使用 new 创建一个对象,您应该考虑在某个地方delete-ing 它(稍后您肯定会了解像 unique_ptr 或 shared_ptr 这样的智能指针,它会照顾你的。)

你可以避免 Person 的构造函数中的 this->,使用你在 Student 中所做的 mem-initializer:

   Person(string firstName, string lastName, int identification)
: firstName(firstName), lastName(lastName), id(identification)
{ // this code starts once all the members are constructed
}

关于c++ - 初学者 C++ 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36608560/

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