重写方法优先 C++

overriden method first c++

本文关键字:C++ 方法 重写      更新时间:2023-10-16

我正在读一本关于 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;
}

我在这里想要的是打电话给员工::p rintData,然后打电话给经理::p rintData...(员工是经理的父类(我没有放 Getters 和 Setters 来减少代码,它不是一个完成的代码,所以 switch 不只有一种情况

您可以使用 :: 调用超类的运算符:

void Manager::printData() {
    Employee::printData();
    cout << "Number of meetings per week: " << NumMeetings << endl;
    cout << "Number of vacation days per year: " << NumVacations << endl;
}

您可以从派生函数调用基函数。

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部分来打印其余部分。