继承依赖于纯虚函数的重载函数
Inheritance with Overloaded Functions That Rely on Pure Virtual Functions
我有一个基础 Write
class,它有一个纯虚函数 write (std::string text)
,需要所有派生的 classes 来实现它。在基础 class 中,有一个重载的 write
函数接受一个 int
并调用纯虚拟 write()
.
在派生的 class 中,我们根据需要实现 write (std::string text)
。
总的来说,我可以调用 console.write("dog\n");
,但我无法在不通过基础 class 名称的情况下使用接受 int 的重载版本来调用它Write
。无论如何要定义这种继承,以便两个 write
函数,一个接受 std::string
和一个接受 int
的函数,而不通过通过Write
class名字,如程序最后一行所示?
我不希望用户能够调用重载的 write(int)' through the
Write` class 名称,如果可能的话。
#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);
}
正常的模式是让你的基础 class 看起来像:
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;
}
}
模式甚至有一个名称 "Non-Virtual Interface" - https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface 有更多关于模式的信息。
我有一个基础 Write
class,它有一个纯虚函数 write (std::string text)
,需要所有派生的 classes 来实现它。在基础 class 中,有一个重载的 write
函数接受一个 int
并调用纯虚拟 write()
.
在派生的 class 中,我们根据需要实现 write (std::string text)
。
总的来说,我可以调用 console.write("dog\n");
,但我无法在不通过基础 class 名称的情况下使用接受 int 的重载版本来调用它Write
。无论如何要定义这种继承,以便两个 write
函数,一个接受 std::string
和一个接受 int
的函数,而不通过通过Write
class名字,如程序最后一行所示?
我不希望用户能够调用重载的 write(int)' through the
Write` class 名称,如果可能的话。
#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);
}
正常的模式是让你的基础 class 看起来像:
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;
}
}
模式甚至有一个名称 "Non-Virtual Interface" - https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface 有更多关于模式的信息。