【发布时间】:2021-12-14 03:37:04
【问题描述】:
#include <iostream>
using namespace std;
class Student
{
protected:
long studentID;
public:
void setStudentID(long s_){ studentID = s_; }
Student(): studentID(0){}
long get_StudentID(){ return studentID; }
};
class Exam : public Student
{
protected:
float mark;
public:
void setMark(float m_){ mark = m_; }
Exam(): mark(0){}
float getMark(){ return mark; }
};
class Sports : public Student
{
protected:
float score;
public:
void setScore(float s_){ score = s_; }
Sports(): score(0){}
float getScore(){ return score; }
};
class Result: public Student, public Exam, public Sports
{
private:
float Total;
public:
float getTotal(){ return getMark() * getScore(); }
void display();
};
void Result::display()
{
cout << "Student ID = " << get_StudentID() << endl;
cout << "Exam Mark = " << getMark() << endl;
cout << "Sports Score = " << getScore() << endl;
cout << "Total Mark = " << getTotal();
}
int main()
{
Result st1;
st1.display();
return 0;
}
我在 Code::Blocks 中编写了这段代码,但它还不完整,但是这个错误说“对 get_StudentID 的引用不明确”让我感到困惑;它出什么问题了? 我应该删除 using namespace 并在所有 (cout, cin & endl) 语句之前插入 std:: 吗?
【问题讨论】:
-
首先,
Sports、anExam和Result都不是Student,所以它们都不应该从Student继承。仅当派生类与其继承的类具有 is a 关系时,才应从类派生。 -
为什么你的类都继承自
Student?无论如何,get_StudentID()是模棱两可的,因为您多次(直接和间接)从Student继承 -
继承不是金锤。您的代码架构是错误的。相反,继承使用组合。
-
当您在
Result::display例程中调用get_StudentID()时,您期望哪个get_StudentID?Student::get_StudentID()一,Exam::Student::get_StudentID()一,还是Sports::Student::get_StudentID()一?该代码是使用继承作为金枪的示例。
标签: c++