2011-12-18 154 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