#include <iostream> void print(int i) { std::cout << "This is an integer: " << i << std::endl; } void print(float f) { std::cout << "This is a float: " << f << std::endl; } int main() { print(42); print(3.14f); return 0; }上面的代码中,我们定义了两个同名的函数`print`,但是它们的参数列表不同,一个接受整数,一个接受浮点数。在调用函数`print`时,编译器会自动根据参数的类型选择调用哪个函数。
#include <iostream> #include <cstdlib> template <typename T> T max(T a, T b) { return a > b ? a : b; } int main() { int x = 42, y = 23; float f = 3.14f, g = 2.71f; std::cout << "Max of " << x << " and " << y << " is " << max(x, y) << std::endl; std::cout << "Max of " << f << " and " << g << " is " << max(f, g) << std::endl; return 0; }上面的代码中,我们定义了一个模板函数`max`,它可以针对整数、浮点数等多种类型进行运算。在调用函数`max`时,编译器会根据参数类型自动推断出要使用哪个具体的函数实现。
#include <iostream> class Shape { public: virtual float calculateArea() { return 0; } }; class Square : public Shape { public: Square(float l) : _length(l) {} virtual float calculateArea() { return _length * _length; } private: float _length; }; class Circle : public Shape { public: Circle(float r) : _radius(r) {} virtual float calculateArea() { return 3.14f * _radius * _radius; } private: float _radius; }; int main() { Shape *s1 = new Square(5); Shape *s2 = new Circle(3); std::cout << "Area of square is " << s1->calculateArea() << std::endl; std::cout << "Area of circle is " << s2->calculateArea() << std::endl; delete s1; delete s2; return 0; }上面的代码中,我们定义了一个基类`Shape`和两个派生类`Square`和`Circle`,它们都实现了函数`calculateArea`。在调用函数`calculateArea`时,我们将基类指针指向派生类对象,可以看到运行时实际调用的是派生类的实现函数。
#include <iostream> class Shape { public: virtual float calculateArea() = 0; }; class Square : public Shape { public: Square(float l) : _length(l) {} virtual float calculateArea() { return _length * _length; } private: float _length; }; class Circle : public Shape { public: Circle(float r) : _radius(r) {} virtual float calculateArea() { return 3.14f * _radius * _radius; } private: float _radius; }; int main() { // Shape *s = new Shape(); // error: cannot instantiate abstract class Shape *s1 = new Square(5); Shape *s2 = new Circle(3); std::cout << "Area of square is " << s1->calculateArea() << std::endl; std::cout << "Area of circle is " << s2->calculateArea() << std::endl; delete s1; delete s2; return 0; }上面的代码中,我们将基类`Shape`中的函数`calculateArea`声明为纯虚函数,从而实现了抽象类。抽象类不能被实例化,只能用作基类来派生出其他类。在调用函数`calculateArea`时,我们将基类指针指向派生类对象,可以看到运行时实际调用的是派生类的实现函数。
本文链接:http://task.lmcjl.com/news/23.html