多态顾名思义多种形态。
即声明一个指向基类的指针,此类中的纯虚函数被其他类继承,指针可以调用继承于此类的于纯虚函数同名的方法
看示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <iostream> #include <string> #include <memory>
using namespace std; class Parent { public: Parent() {}; string name; virtual void printName() = 0; int age = 88; int getAge() { return age; } };
class Son1 : public Parent { public: Son1(string name): name(name) {}; string name = "zhangsan"; void printName() override { cout << name << endl; }
};
class Son2 : public Parent { public: Son2() {}; int age = 8; int getAge() { return age; } string name = "wangwu"; void printName() override { cout << name << endl; } };
int main() { shared_ptr<Parent> son2; son2 = make_shared<Son2>(); son2->printName(); cout << son2->getAge() << endl; return 0; }
|