C++基类指针容器中,编辑特定对象的属性

C++ base class pointer container, edit attributes of specific object

本文关键字:对象 属性 编辑 指针 基类 C++      更新时间:2023-10-16

我有一个动物基类和派生类,叫做 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);
}

在这种情况下,更好的解决方案是读取文件一次并将内容提供给不同的类。