简体   繁体   English

依赖纯虚拟函数的重载函数的继承

[英]Inheritance with Overloaded Functions That Rely on Pure Virtual Functions

I have a base Write class that has a pure virtual function write (std::string text) that requires all derived classes to implement it. 我有一个基本Write类,该类具有纯虚拟函数write (std::string text) ,需要所有派生类来实现它。 In the base class, there is an overloaded write function that takes in an int and calls the pure virtual write() . 在基类中,有一个重载的write函数,该函数接受一个int并调用纯虚拟write()

In the derived class, we implement the write (std::string text) , as required. 在派生类中,我们根据需要实现write (std::string text)

In the main, I'm able to call console.write("dog\\n"); 总的来说,我可以调用console.write("dog\\n"); , but I'm not able to call it with the overloaded version that takes in an int without going through the base class name Write . ,但是我无法在不经过基类名称Write情况下使用带有int的重载版本来调用它。 Is there anyway to define this inheritance so that both write functions, one that takes in a std::string and one that takes in an int without giving away the details of the inheritance by going through the Write class name, as shown on the last line of the program? 无论如何定义继承,以便两个write函数,一个接受std::string函数,一个接受int函数,而不需要通过Write类名来给出继承的细节,如最后一个所示。程序行?

I don't want the user to be able to call the overloaded write(int)' through the Write` class name, if possible. 我不希望用户能够write(int)' through the Write类名来调用重载的write(int)' through the

#include <iostream>

class Write
{
protected:
    virtual void write (const std::string &text) = 0;

public:
    void write (const int &number)
    {
        write (std::to_string (number));
    }
};

class Console_Write : public Write
{
public:
    void write (const std::string &text) override
    {
        std::cout << text;
    }
};

int main()
{
    Console_Write console;
    console.write("dog\n");
    console.Write::write (1); // Is it possible to be able to change the inheritance so we can just call: console.write (1);
}

The normal pattern for this would be having your base class look something like: 正常的模式是让您的基类如下所示:

class Write {
 public:
  virtual ~Write() = default;
  void write(const std::string& str) {
    write_internal(str);
  }
  void write(int n) {
    write(std::to_string(n));
  }
 private:
  virtual void write_internal(const std::string& str) = 0;
}

class ConsoleWrite : public Write {
 public:
  ~ConsoleWrite() = default;
 private:
  void write_internal(const std::string& str) {
    std::cout << str;
  }
}

The pattern even has a name "Non-Virtual Interface" - https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface has more information about the pattern. 该模式甚至有一个名称“非虚拟接口” -https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface具有有关该模式的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM