我最近开始学习面向对象的编程,现在我遇到了一些困难。我所要做的就是在数组中放入继承相同基数的不同类,然后在屏幕上显示数组中具有特定特征的所有成员。我的数组看起来像:
[first person1("John",true)] [second person2("Michael",false)] [first person3("Tanya",false)], ...;
然后我想使用方法getInfo()显示数组的所有成员,如:
for(int i=0;i < numberOfElements;i++) array[i].getInfo();
// where numberOfElements will be incremented in the constructor
我怎么能这样做?
#include <iostream>
#include <string>
using namespace std;
class base
{
protected: string name;
public: virtual string getName()=0;
};
class first:public base
{
protected: bool Medic;
public: first(string Name="",bool check=false) {name=Name; Medic=check;};
public: virtual string getName() {return name;};
public: bool isMedic() {return Medic;};
public: void getInfo()
{
cout << endl << name;
if(Medic) cout << " is medic.";
else cout << " is not a medic.";
};
};
class second:public base
{
protected: bool Janitor;
public: second(string Name="",bool check=false) {name=Name; Janitor=check;};
public: virtual string getName() {return name;};
public: bool isMedic() {return Janitor;};
public: void getInfo()
{
cout << endl << name;
if(Medic) cout << " is a janitor.";
else cout << " is not a janitor.";
};
};
int main()
{
base* a[100];
// Code
return 0;
}
答案 0 :(得分:0)
您需要使用适当的类类型调用new
,如下所示:
int main()
{
base* a[100];
a[0] = new first("Janit", false);
a[1] = new second("Romeo", true);
return 0;
}
但是,在打印时,由您决定如何确定a[i]
类型是什么!稍后您可以通过为每个元素调用delete
来释放内存:
delete a[i];
它不等同于以下任何一个:
delete []a;
delete a;
delete []a[i];
请注意,这只是您继续进行的起点,而不是完整的解决方案。