c++ - 抽象具有不同返回类型的成员函数

标签 c++ inheritance

如果我有以下 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/

相关文章:

c++ - 如何从标识符创建类?

java - isEmpty() 的实现

java - 如何扩展一个 java 类来扩展 Scala 中另一个类的类型参数?

java - 将 C++ 函数翻译成 Java

c++ - 如何从 C++ 模板中的方法类型推断类类型?

c++ - 交换 bool 值

C# 继承和重写基本属性

c++ - 运算符重载 "new"C++

c++ - 无法使用 Microsoft CodeGen 使用 Visual Studio 2015 和 Clang 3.7 构建 Google Test

c++ - 这个 C++ 标识符是如何未定义的?