在子类中调用父函数

Call parent function inside of child class

本文关键字:函数 调用 子类      更新时间:2023-10-16
class Parent;
class Child;
Parent *parent;
ifstream inf("file.csv");
inf >> *parent;
//in parent class
friend istream& operator>> (istream &is, Parent &parent) {
  return parent.read(is);
}
virtual istream& read(istream &is){
  char temp[80];
  is >> temp;
  // then break temp into strings and assign them to values
  return is;
}
//virtual istream& read

它仅读取前两个值并将其分配给父类。 Child类有自己的Parent类值 + 3。

如何调用我调用父级的read()函数,然后调用子级的read()函数,以便父级函数读取文件中的前 2 个字段,子函数读取接下来的 3 个字段?

我知道这是语法问题;我只是不知道该怎么做。我试过在孩子阅读课内打电话给Parent::read(is),我试过在孩子read()之前打电话;我试过read(is) >> temp但没有一个奏效。当我调用Parent::read(is)然后is >> temp时,父is将返回文件的所有 5 个值。

在这种情况下,

您通常会让 Child 覆盖 Parent 中的 read 函数。这允许派生类在应用其自己的逻辑之前调用父类中的原始函数。

class Parent
{
public:
    virtual void read(istream &s)
    {
        s >> value1;
        s >> value2;
    }
};
class Child : public Parent
{
public:
    virtual void read(istream &s)
    {
        Parent::read(s);  // Read the values for the parent
        // Read in the 3 values for Child
        s >> value3;
        s >> value4;
        s >> value5;
    }
};

执行读取操作"

// Instantiate an instance of the derived class
Parent *parent(new Child);
// Call the read function. This will call Child::read() which in turn will
// call Parent::read() 
parent->read(instream);