简体   繁体   中英

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. In the base class, there is an overloaded write function that takes in an int and calls the pure virtual write() .

In the derived class, we implement the write (std::string text) , as required.

In the main, I'm able to call 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 . 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?

I don't want the user to be able to call the overloaded write(int)' through the Write` class name, if possible.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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