2011-12-18 117 views
2

一個成員函數如果我有下面的C++類:抽象與不同的返回類型

class FileIOBase 
{ 
    //regular file operations 
    // 
    //virtual fstream/ifstream/ofstream getStream(); ??? 
    // 
    bool open(const std::string &path); 
    bool isOpen() const; 
    void close(); 
    ... 
}; 

class InputFile : FileIOBase 
{ 
    size_t read(...); 
    ifstream getStream(); 
}; 

class OutputFile : FileIOBase 
{ 
    size_t write(...); 
    ofstream getStream(); 
}; 

class InputOutputFile : virtual InputFile, virtual OutputFile 
{ 
    fstream getStream(); 
}; 

的類只是封裝在標準,出,入/出文件流和它們的操作。

有什麼辦法使界面的getStream()的一部分,它進入FileIOBase?

+1

如果可以,有什麼你想用'FileIOBase :: getStream()'的結果嗎? – 2011-12-18 23:14:02

+1

@OliCharlesworth在我看來'FileIOBase'應該是抽象的,因此它可能是純虛擬的。 (這不是真的有助於實現它,但會回答你的語義問題。) – 2011-12-18 23:16:56

+0

什麼都沒有!我只是想將它添加到接口來​​強制派生類的實現。我知道我可以像往常一樣將它們添加到派生類中。並且由於派生類的數量有限,所以它實際上是有意義的,但我只是好奇而已! – p00ya00 2011-12-18 23:18:18

回答

3

我想你的意思是讓那些返回值的引用而不是值。如果是這樣的話,你可以有getStream基類返回ios&,那麼你可以有具體的函數返回fstream&ifstream&ofstream&因爲他們是協變與ios&

class FileIOBase 
{ 
    ... 
    bool open(const std::string &path); 
    bool isOpen() const; 
    void close(); 

    virtual ios& getStream() = 0; 
    ... 
}; 

class InputFile : FileIOBase 
{ 
    size_t read(...); 
    ifstream& getStream(); 
}; 

class OutputFile : FileIOBase 
{ 
    size_t write(...); 
    ofstream& getStream(); 
}; 

class InputOutputFile : virtual InputFile, virtual OutputFile 
{ 
    fstream& getStream(); 
}; 
+2

+1表示解決問題的答案。 OP現在需要弄清楚這是否確實爲他們提供了任何有用的用途...... – 2011-12-18 23:28:56

+0

有沒有針對這種情況的一般解決方案?例如使用通用編程技術。 – p00ya00 2011-12-18 23:34:58

+0

@ p00ya00你的意思是什麼情況? – 2011-12-18 23:44:04