2012-06-04 62 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);