C++基类指针容器中,编辑特定对象的属性
C++ base class pointer container, edit attributes of specific object
我有一个动物基类和派生类,叫做 Cat 和 Dog。 display() 和 readfile() 都是这两个类中的虚函数。
目前,一旦调用readfile(),屏幕上只显示"Kay"。如何以某种方式读取文件中的所有行,以便我可以在向量中找到一个项目,然后对其进行编辑,例如,如果我想通过运行名为 changeName() 的函数将"Sugar"更改为"Sopa"例如?
Cat.csv
Kay
Sugar
Jo
int main()
{
AnimalCollection coll;
std::ifstream file("Cat.csv");
Cat *cat = new Cat("CAT");
Dog *dog = new Dog("DOG");
coll.push_back(cat);
coll.push_back(dog);
for (Animal *c : coll)
{
c->display();
}
for (Animal *c : coll)
{
c->readfile(file);
}
return 0;
}
这个问题缺少一个重要的部分。
就像@KennyOstrom指出的那样,该文件似乎只被读取了一次。file.seekg(0, file.beg);
可以提供帮助。
这是在解决你的问题吗?
for (Animal *c : coll)
{
c->readfile(file);
file.seekg(0, file.beg);
}
在这种情况下,更好的解决方案是读取文件一次并将内容提供给不同的类。
相关文章:
- 类对象属性是否可以调用返回属性应具有的值的方法C++?
- 对象属性同级访问
- 迭代 Napi::对象属性(键)在 Node.js C++ N-API 中
- 是否可以在C++(17)中捕获某些对象属性的破坏性赋值事件
- 分配以下对象属性在哪里
- sutex作为对象属性和对象的向量
- C++ - 在类中包含不是类对象属性的变量是否是一种不好的做法
- 根据对象属性从列表中删除对象
- 将对象属性替换为列表
- 查找对象属性是否位于对象向量C++中
- 未知EABI对象属性44
- 按矢量中的对象属性合并排序
- 如何访问带有静态回调的对象属性
- c++中对象属性的内存分配
- 为什么对象属性的值在 c++ 中将其指针添加到映射后返回零
- 如何检查对象属性更新是否存在 std::map 键,否则插入一个新键?
- 从ASP.NET应用程序查询Active Directory对象属性将返回旧结果
- 性能对象属性与范围变量
- 无法访问对象属性
- 如何从对象方法中访问对象属性