从文件中读取的多态性
Polymorphism read from file
如果我正在将从父类派生的类写入文件,如何确定我从文件中读取哪个类?
基本上我有 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"不能是它的属性之一,因此必须在构造函数终止之前放回流中)。
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- C++ 泛型和多态性:这种模式可行吗?
- 为什么我们实际上需要运行时多态性?
- 如何在这个简单的最小示例中实现多态性?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 无法初始化已知大小的矢量指针,该大小不会因多态性而更改
- 运行时多态性和dynamic_cast需要澄清
- 如何调用指针类型的方法(禁用多态性)?
- 从基类调用函数的多态性
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 从文件中读取的多态性