在子类中调用父函数

时间:2012-06-04 04:02:45

标签: c++ inheritance csv ifstream

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。

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

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

1 个答案:

答案 0 :(得分:0)

在这种情况下,您通常会使用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);