2012-06-04 59 views
-1
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个值。

+1

所有的'A,B,C,d,E,G,DF,DS,VD,bn'变量..这是不好的风格。请写下如下内容:'in_file'(无法理解,但假设它是输入文件)或'input_file'或'inputFile'或其他... – gaussblurinc

+0

IIRC Parent :: method()应​​该工作 – rossum

+0

我认为Parent :: method()只会调用Parent的一个静态方法,为了调用Parent的阅读版本,我认为你需要将你的Child转换为Parent,然后通过Parent ref调用read,如'Child c;父(c).read()/ *应调用父方法* /; c。 read()/ *应该调用Child方法* /;'。我在这里假设Child从Parent继承,虽然问题中的声明没有指出。 –

回答

0

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