存储在父类中的派生类数组

Array of derived class stored in parent class

本文关键字:派生 数组 父类 存储      更新时间:2023-10-16

我不太明白如何在父类中存储派生类的数组。我一直得到错误

错误C3646 'list':未知的覆盖说明符
错误C2065 'list':未声明的标识符

下面是我的代码

#include <iostream>
#include <string>
using namespace std;
class GameScores
{
public:
    GameEntry list[9];
    void inputList(GameEntry x);
    void sortList();
    void removeList(int r);
    void printList();
    GameScores();
};
class GameEntry :public GameScores
{
public:
    GameEntry(const string& n = "", int s = 0, const string d = "1/1/99");
    string getName() const;
    int getScore() const;
    string getDate() const;
    string setName(string n);
    int setScore(int s);
    string setDate(string d);
private:
    string name;
    int score;
    string date;
};
GameScores::GameScores()
{
    GameEntry list[9];
}
void GameScores::inputList(GameEntry x)
{
    for (int i = 0; i < 10; i++)
        if (x.getScore() >= list[i].getScore())
        {
            list[i + 1] = list[i];
            list[i] = x;
        }
}
void GameScores::sortList()
{
    GameEntry swap;
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10 - 1; j++)
        {
            if (list[j].getScore() > list[j].getScore() + 1)
            {
                swap = list[j];
                list[j] = list[j + 1];
                list[j + 1] = swap;
            }
        }
    }
}
void GameScores::removeList(int r)
{
    for (int i = r; i < 10; i++)
    list[i - 1] = list[i];
    list[9].setScore(0);
    list[9].setName(" ");
    list[9].setDate(" ");
}
void GameScores::printList()
{
    cout << "Top Scores" << endl;
    for (int i = 0; i < 10; i++)
        cout << list[i].getScore() << " " << list[i].getName() << " " << list[i].getDate() << endl;
}
GameEntry::GameEntry(const string& n, int s, const string d)    // constructor
    : name(n), score(s), date(d) { }
                                                                // accessors
string GameEntry::getName() const { return name; }
int GameEntry::getScore() const { return score; }
string GameEntry::getDate() const { return date; }
string GameEntry::setName(string n)
{
    name = n;
}
int GameEntry::setScore(int s)
{
    score = s;
}
;
string GameEntry::setDate(string d)
{
    date = d;
}
int main()
{
    GameEntry p1("John", 90, "9/9/98"), p2("Jane", 95, 8/21/98), p3("Bob", 60, "7/11/99"), p4("Jo", 92, "6/4/97");
    GameScores topScores;
    topScores.inputList(p1);
    topScores.inputList(p2);
    topScores.inputList(p3);
    topScores.inputList(p4);
    topScores.printList();
    return 0;
}

这个设计很有问题。让第二个类继承第一个类的目的是什么?看起来,您最终会得到数组的每个成员都包含一个带有其所有兄弟数组的附加数组。难道你不想要一个数组吗?你需要从更早的角度重新考虑这个问题。

如果你真的有理由让父类包含子类的数组,也许你应该定义一个两个类都实现的接口(抽象基类)

要在GameScores类中使用GameEntry作为类型,必须像这样向前声明该类:

class GameEntry;
class GameScores
{
public:
    GameEntry list[9];
    void inputList(GameEntry x);
    void sortList();
    void removeList(int r);
    void printList();
    GameScores();
};