C++多态实例

#include <iostream> 
#include <string> 
using namespace std;

//class 实现 
class Employee
{
    string name;
public:
    Employee(string n);
    virtual void print();
};

//class 成员函数实现 
Employee::Employee(string n) :name(n)//初始化成员列表  
{
    //name = n;     
}
void Employee::print() 
{
    cout << name << endl;
}

//class 实现 
class Manager: public Employee
{
    int level;
public:
    Manager(string n, int l = 1);
    //virtual void print(); 
    void print();
};

//class 成员函数实现 
Manager::Manager(string n, int l) :Employee(n), level(l) 
{
}

void Manager::print()
{
    cout << level << "\t";
    Employee::print();
}
////派生类的构造函数只能描述它自己的成员和其直接基类的初始式,不能去初始化基类的成员。 
//Manager::Manager(string n, int l) : name(n), level(l) 
//{
//}


int main() 
{
//    Manager m("Zhang",2);
//    Employee e("Li");
//    m.print();
//    e.print();
//    
//    cout<<"ok-----------"<<endl; 
//    
//    Employee *p=&e;
//    p->print();
//    cout<<"ok-2222----------"<<endl; 
//    
//    p=&m;
//    p->print();
//    
//    cout<<"ooo"<<endl;
//    
//    Manager *q=&m;
//    q->print();
    
//    Employee *employees[100];
//    int num = 0;
//    
//    employees[num] = &e;
//    num++;
//    employees[num] = &m;
//    num++;

    ///////////////////////////////////////////
    
    Employee* employees[100]; 
    int e_num = 0;
    Employee* pe;
    string name; 
    
    int level;
    char cmd;
    
    cout << "input cmd" << endl;
    
    
    while (cin >> cmd)
    {
        if (cmd == 'M' || cmd == 'm') 
        {
            cout << "input name and level" << endl;
            cin >> name >> level;
            pe = new Manager(name, level);
            employees[e_num] = pe; 
            e_num++;
        }
        else if (cmd == 'e' || cmd == 'E') 
        {
            cout << "input name" << endl;
            cin >> name;
            pe = new Employee(name);
            employees[e_num] = pe; 
            e_num++;
        }
        else 
            break;
        cout << "input cmd" << endl;
    }
    for (int i = 0; i < e_num; i++) 
    {
        employees[i]->print();
    }
    
    return 0;    
}

 

input cmd
M
input name and level
li 3
input cmd
m
input name and level
rr
4
input cmd
e
input name
bffd
input cmd
e
input name
sdfsdfsdf
input cmd
s
3 li
4 rr
bffd
sdfsdfsdf

通过基类指针Employee *pe可以指向基类和派生类。从而达到多态的效果。后面s后的就是输出的结果。

原文链接: https://www.cnblogs.com/CodeWorkerLiMing/p/10998452.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++多态实例

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/296488

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午5:55
下一篇 2023年2月15日 下午5:55

相关推荐