如果我有以下 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() 成为接口(interface)的一部分并将其移动到 FileIOBase 中?
最佳答案
我认为您的意思是使这些返回值引用而不是值。如果是这种情况,您可以让基类中的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();
};
关于c++ - 抽象具有不同返回类型的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8555605/