我得到了两个类,Person和Student,其中Person是基类,而Student是派生类。不允许对Person类或main函数进行任何更改。注意到Student继承了Person的所有属性。一个学生类构造函数,它有参数:一个字符串,名字一个字符串,姓氏一个整数,id。测试分数的整数数组(或向量)。char calculate()方法,该方法计算学生对象的平均值,并返回代表其计算平均值的年级字符。示例输入-
Heraldo Memelli 8135627 2 100 80
预期输出-
Name: Memelli, Heraldo ID: 8135627 Grade: O
我得到的错误是在声明构造函数的时候,你能解释一下为什么吗,还有你建议的其他方法吗?提前谢谢。这是我的代码-
#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 firstName, string lastName, int identification, vector < int > & scores) {
for (int i = 0; i < & scores.size(); i++)
this - > testScores.pushback( & scores[i]);
}
char calculate() {
int avg, sum = 0, count = 0;
for (int i = testScores.begin(); i < testScores.size(); i++) {
sum = sum + testScores[i];
count++;
}
avg = sum / count;
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 if (avg0 < 40)
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);
}
Student * s = new Student(firstName, lastName, id, scores);
s - > printPerson();
cout << "Grade: " << s - > calculate() << "\n";
return 0;
}
发布于 2020-04-29 18:45:01
Person
类没有默认构造函数,因此必须使用Person
类型的子对象的参数在内存初始化器列表中Student
类的构造函数中显式调用该构造函数。
构造函数可以采用如下方式
Student( const std::string &firstName,
const std::string &lastName,
int identification,
const std::vector<int> &scores )
: Person( firstName, lastName, identification ), testScores( scores )
{
}
成员函数可以定义如下
char calculate() const
{
long long int sum = 0;
for ( const auto &item : testScores )
{
sum += item;
}
long long int avg = testScores.size() == 0 ? 0 : sum / testScores.size();
char c;
if ( avg >= 90 )
c = 'O';
else if ( avg >= 80 )
c = 'E';
else if ( avg >= 70 )
c ='A';
else if ( avg >= 55 )
c = 'P';
else if ( avg >= 40 )
c = 'D';
else
c = 'T';
return c;
}
至于你的代码,例如下面的循环
for (int i = 0; i < & scores.size(); i++)
this - > testScores.pushback( & scores[i]);
是无效的,因此不应进行编译,至少因为您正在尝试获取由成员函数size
返回的右值的地址。
发布于 2020-04-29 18:56:06
我认为很明显,你期望你的Student对象是一个给定名字的人,但是在你的代码中,你在哪里提到了这一点呢?未使用firstName
、lastName
和identitfication
参数。下面是你应该怎么做
Student(string firstName, string lastName, int identification, vector < int > & scores) :
Person(firstName, lastName, identification) {
...
}
https://stackoverflow.com/questions/61509068
复制相似问题