我正在读一本关于c ++编程的书,有一个应该用虚拟解决的练习:
//Main.cpp
#include "stdafx.h"
#include "Employee.h"
#include "Manager.h"
#include <vector>
#include <iostream>
#include <stdlib.h>
using namespace std;
//Generates the choice of which type of employee we are working on.
int generate_type_choice() {
cout << "1.Manager" << endl;
cout << "2.Enginner" << endl;
cout << "3.Researcher" << endl;
int choice=0;
cin >> choice;
return choice;
}
void addEmployee(vector<Employee*>* v) {
int choice = generate_type_choice();
cout << "first name: ";
string Fname;
cin.ignore();
getline(cin, Fname);
string Lname;
cout << "Last Name: ";
getline(cin, Lname);
cout << "Salary: ";
float s;
cin >> s;
switch (choice) {
case 1: {
cout << "Number of Meetings per week: ";
int m,vac;
cin >> m;
cout << "Number of vacation days per year: ";
cin >> vac;
Employee* e = new Manager(Fname, Lname, s, m, vac);
(*v).push_back(e);
break;
}
}
(*v).push_back(new Employee(Fname, Lname, s));
}
void printVector(vector<Employee*> v) {
for each (Employee* e in v)
{
(*e).printData();
}
}
int main()
{
vector<Employee*> v;
int choice = 0;
cout << "1.Add Employee" << endl;
cin >> choice;
switch (choice) {
case 1: {
addEmployee(&v);
}
}
printVector(v);
system("pause");
return 0;
}
//Employee.cpp
#include "stdafx.h"
#include "Employee.h"
#include <string>
#include <iostream>
using namespace std;
Employee::Employee()
{
Fname = "NoName";
Lname = "NoName";
salary = 0;
}
Employee::Employee(string f, string l, float s) {
Fname = f;
Lname = l;
salary = s;
}
void Employee::printData() {
cout << "First Name: " << Fname << endl;
cout << "Last Name: " << Lname << endl;
cout << "salary: " << salary << endl;
}
//Manage.cpp
#include "stdafx.h"
#include "Manager.h"
#include <string>
#include <iostream>
using namespace std;
Manager::Manager()
{
NumMeetings=0;
NumVacations=0;
}
void Manager::printData() {
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
}
我想要的是调用employee :: printData,之后调用Manager :: printData ... (员工是经理的父级) 我没有使用Getters和Setters来减少代码,而且它不是一个完成的代码,所以切换只有一个案例
答案 0 :(得分:0)
您可以使用::
来调用超类&#39;操作者:
void Manager::printData() {
Employee::printData();
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
}
答案 1 :(得分:0)
您可以从派生函数调用基函数。
void Manager::printData() {
cout << "Number of meetings per week: " << NumMeetings << endl;
cout << "Number of vacation days per year: " << NumVacations << endl;
Employee::printData();
}
将打印Manager
部分,然后Employee::printData();
将仅使用对象的printData
部分调用Employee
来打印其余部分。