如果我正在将从父类派生的类写入文件,如何确定我从文件中读取哪个类?
基本上我有 3 个派生类:DerivedA
、DerivedB
、DerivedC
。写入文件时,我这样做了:
DerivedA attribute1 attribute2 attribute9 DerivedB attribute5 attribute6 DerivedC attribute4 attribute7
如何设置 if 语句以确定我目前正在哪个班级阅读?
编辑:
我正在为每个家庭建立一个具有特定不同属性的房屋列表。
list<Homes*> home;
Homes *tmp;
while(ins>>tmp)
{//determine which home it is
tmp=new ***//depends on which derived class it is;
}
在我的数据文件中,它会说:
Brickhome
solar panels
3 bathrooms
Spiral Staircase
LogCabin
gravel driveway
fireplace
Castle
10 butlers
1 moat
我需要一种方法来确定需要创建哪个家。
在读取命名它的行之前,您无法知道要构造哪个派生类型。你可以做的是有一个函数来读取第一行,然后将其余部分委托给相应的子类构造函数。
list<Homes*> home;
string str;
while(ins >> str)
{
switch(str)
{
Homes *tmp;
case "Brickhome":
tmp = new Brickhome(ins);
break;
case "LogCabin":
tmp = new LogCabin(ins);
break;
case "Castle":
tmp = new Castle(ins);
break;
default:
throw("unknown type of home");
}
home.push_back(tmp);
}
请注意,子类必须有一种明智的方法来知道何时停止(例如 Brickhome
必须知道它有多少属性,或者知道"LogCabin"不能是它的属性之一,因此必须在构造函数终止之前放回流中)。