存储在父类中的派生类数组
Array of derived class stored in parent class
我不太明白如何在父类中存储派生类的数组。我一直得到错误
错误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();
};
相关文章:
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 如何使用数据成员填充派生类的对象到基类的指针数组中
- std::数组派生类聚合初始化
- 指向不同派生类的指针数组
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 从基类数组调用派生函数
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 如何在C 中的派生类中分配数据成员数组
- 在C 中的数组中存储抽象基类的不同派生类的对象
- 使用数组作为对象调用派生类的方法
- 我怎么知道基类对象的指针数组中元素的类型,它将为派生类分配内存
- 如何将基类指针数组强制转换为派生类
- 如何使数组的派生类型接受聚合初始化?
- 指向基类数组的指针,填充派生类
- 在单个指针数组中调用不同派生类的虚拟方法
- 基类的C++数组,该数组的元素中存储有派生类的实例
- 基类和派生类的二维动态数组
- 将派生对象添加到(抽象的)基指针数组中
- 如何对派生模板类C++中的对象数组进行排序
- 矢量强制转换与派生对象到基对象的数组转换