#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后的就是输出的结果。