多态
在C++中,多态是指相同的接口可以用于表示对象的多种形式。多态可以分为两种:编译期多态(Compile-time polymorphism)和运行时多态(Run-time polymorphism)。下面对这两者进行解释。
- 编译期多态(Compile-time polymorphism):
-
函数重载: 当同一个作用域内有两个或多个函数名称相同但参数列表不同的函数时,我们说这些函数是重载的。编译器会根据调用的参数列表来决定调用哪个函数。
1 2 3 4 5 6 7
void print(int i) { std::cout << "Here is int: " << i << std::endl; } void print(double d) { std::cout << "Here is double: " << d << std::endl; }
-
运算符重载: 你可以为用户定义的数据类型提供适当的运算符。
1 2 3 4 5 6 7 8 9 10 11 12
class Complex { private: float real; float imag; public: Complex operator + (Complex const &obj) { Complex temp; temp.real = real + obj.real; temp.imag = imag + obj.imag; return temp; } };
-
模板: 通过使用模板,你可以创建一个函数模板或类模板,使其适用于任何数据类型。
1 2 3 4
template <typename T> T max(T x, T y) { return (x > y) ? x : y; }
-
运行时多态(Run-time polymorphism):
-
虚函数与继承: 运行时多态是通过使用指向基类的指针或引用来调用派生类中的函数实现的。为了实现运行时多态,基类中的函数必须被声明为
virtual
。这样,当基类指针或引用指向派生类对象时,就会调用派生类中的这个函数。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Base { public: virtual void show() { std::cout << "Base class" << std::endl; } }; class Derived : public Base { public: void show() { std::cout << "Derived class" << std::endl; } }; // 使用: Base* bptr; Derived d; bptr = &d; bptr->show(); // 输出 "Derived class"
-
纯虚函数与抽象类: 纯虚函数是在基类中声明的虚函数,它没有定义。拥有纯虚函数的类被称为抽象类,不能为此类创建对象。
总结:编译期多态在编译时解析,而运行时多态在程序运行时解析。编译期多态主要包括函数重载、运算符重载和模板,而运行时多态是通过虚函数来实现的。