是的,重载是一种静态多态(编译时多态).但是,在C++中,表达式"多态类"是指具有至少一个虚拟成员函数的类.即,在C++中,术语"多态"与动态多态性密切相关.
术语覆盖用于提供虚拟功能的派生类特定实现.从某种意义上说,它是一种替代品.一个过载,相反,只是提供了一个函数名的¹additional意义.
动态多态的示例:
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;
}
Run Code Online (Sandbox Code Playgroud)
静态多态性的例子:
#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(); }
Run Code Online (Sandbox Code Playgroud)
注意:
¹除非它影响基类提供的含义.