C++之多态性

    技术2022-07-11  142

    多态的体现 编译时多态:重载 运行时多态:继承关系,虚函数,指针或引用

    1.多态性之纯虚函数

    #include<iostream> using namespace std; class salary { int ks; public: salary(int k) {ks = k; } int gets() { return ks; } virtual void show() = 0;//纯虚函数,不能创建函数) }; class js :public salary { public: js(int k):salary(k){ } void show() { cout << 5000 + gets() *50 << endl;} }; class fjs :public salary { public: fjs(int k) :salary(k) { } void show() { cout << 3000 + gets() * 30 << endl; } }; class s :public salary { public: s(int k) :salary(k) { } void show() { cout << 2000 + gets() * 20 << endl; } }; int main() { salary* p; js a(5); fjs b(10); s c(15); p = &a; p->show(); p = &b; p->show(); p = &c; p->show(); return 0; }

    2.多态性之虚函数

    #include<iostream> using namespace std; class salary { string m, p; int ks; public: salary(string name,string place,int k = 0) { m = name, p = place, ks = k; } int gets() { return ks; } void mshow() { cout << m << " " << p << " "; } //为了方便使用多态特性,需要在基类中定义虚函数。 virtual void show() = 0; }; class js :virtual public salary { int t; public: js(string name, string place, int tm):salary(name,place) { t = tm; } void show() { mshow(); cout << t * 50 << endl; } }; class jj :virtual public salary { int n; public: jj(string name, string place, int num) :salary(name, place) { n = num; } void show() { mshow(); cout << n * 100 << endl; } }; class gd :virtual public salary { int s; public: gd(string name, string place, int g) :salary(name, place) { s = g; } void show() { mshow(); cout << s << endl; } }; int main() { salary* p; //父类的指针指向其子类的实例,然后通过父类的指针调用实际子类的成员函数 js a("zhangsan","taiyuan",140); jj b("zhangsi", "hangzhou", 65); gd c("qsd", "lvliang", 5000); p = &a; p->show(); p = &b; p->show(); p = &c; p->show(); return 0; }
    Processed: 0.032, SQL: 10