[英]C++ polymorphism and overloading?
Can overloading be considered as an implementation of polymorphism? 可以将重载视为多态的实现吗? If they are the same then why are two different words used? 如果它们相同,那么为什么要使用两个不同的词?
Yes, overloading is a form of static polymorphism (compile time polymorphism). 是的,重载是静态多态 (编译时多态)的一种形式。 However, in C++ the expression “polymorphic class” refers to a class with at least one virtual member function. 但是,在C ++中,“多态类”一词是指具有至少一个虚拟成员函数的类。 Ie, in C++ the term “polymorphic” is strongly associated with dynamic polymorphism . 即,在C ++中,术语“多态”与动态多态性密切相关。
The term override is used for providing a derived class specific implementation of a virtual function. 术语“ 覆盖”用于提供虚拟功能的派生类特定的实现。 In a sense it is a replacement. 从某种意义上说,它是一种替代。 An overload , in contrast, just provides an ¹additional meaning for a function name. 相比之下, 重载只是为函数名称提供了“附加含义”。
Example of dynamic polymorphism: 动态多态性的示例:
struct Animal
{
virtual auto sound() const
-> char const* = 0;
};
struct Dog: Animal
{
auto sound() const
-> char const* override
{ return "Woof!"; }
};
#include <iostream>
using namespace std;
auto main()
-> int
{
Animal&& a = Dog();
cout << a.sound() << endl;
}
Example of static polymorphism: 静态多态的示例:
#include <iostream>
using namespace std;
template< class Derived >
struct Animal
{
void make_sound() const
{
auto self = *static_cast<Derived const*>( this );
std::cout << self.sound() << endl;
}
};
struct Dog: Animal< Dog >
{
auto sound() const -> char const* { return "Woof!"; }
};
auto main()
-> int
{ Dog().make_sound(); }
Notes: 笔记:
¹ Except when it shadows the meanings provided by a base class. ¹除非它掩盖了基类提供的含义,否则它不起作用。
Yes, overloading is a form of static polymorphism, Ad hoc polymorphism to be precise. 是的,重载是静态多态的一种形式,确切地说是Ad hoc多态 。
It is NOT dynamic polymorphism (Subtyping), which is what people usually refer to in the context of C++. 它不是动态多态性(子类型化),人们通常在C ++中引用它。
https://en.wikipedia.org/wiki/Polymorphism_(computer_science) https://zh.wikipedia.org/wiki/多态性_(computer_science)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.