首页 > 解决方案 > 虚函数和向量(C++)

问题描述

我在下面有这两个类,研究人员来自员工。我试图让 print 为许多不同的派生员工类单独工作。当我在下面的 main 中使用此方法时,虚拟打印功能按我的意愿工作。

Employee* empVec[10];
empVec[0] = new researcher("Hal", "Norman", 40, "ThePhd", "theThesis");
empVec[0]->print();
cout << endl;
empVec[1] = new Employee("Emp", "loyee", 25);
empVec[1]->print();

//TERMINAL
Name: Hal Norman
Salary: $40
PHD: ThePhd
Thesis: theThesis

Name: Emp loyee
Salary: $25

但是,当我尝试将它与向量一起使用时,它却给了我这个结果。

vector<Employee> empVec;
empVec.resize(10);
researcher res("Hal", "Norman", 40, "ThePhd", "theThesis");
empVec[0] = res;
empVec[0].print();
cout << endl;
Employee emp("Emp", "Loyee", 25);
empVec[1] = emp;
empVec[1].print();

//terminal

Name: Hal Norman
Salary: $40

Name: Emp Loyee
Salary: $25

我想用向量尝试这个​​项目,但我不知道该怎么做。提前致谢

//EMPLOYEE.H
#ifndef _EMPLOYEE_H_
#define _EMPLOYEE_H_

#include <iostream>
#include <string>

using namespace std;



class Employee
{
public:
    string Fname; //First Name
    string Lname; //Last Name
    int Salary; //Salary

    Employee(string Firstname, 
             string Lastname, 
             int sal); //Constructor
    Employee();  //Constructor
    ~Employee();
    virtual void print();
};

#endif



//RESEARCHER.H
#ifndef _RESEARCHER_H_
#define _RESEARCHER_H_

#include <iostream>
#include <string>

#include "Employee.h"

class researcher :
    public Employee
{
public:
    researcher(string firstName,
               string lastName,
               int sal,
               string PHD,
               string thesis); //constructor
    researcher(); //default
    ~researcher(); //destructor
    void print();

private:
    string phd;
    string phdThesis;

};

#endif


//EMPLOYEE.CPP
#include <iostream>
#include <string>
#include "Employee.h"


Employee::Employee(string FirstName,
                   string LastName, 
                   int sal)
{
    Fname = FirstName;
    Lname = LastName;
    Salary = sal;
}

Employee::Employee()
{
    Fname = "First Name";
    Lname = "Last Name";
    Salary = 0;
}


Employee::~Employee()
{

}

void Employee::print() 
{
    cout << "Name: " << Fname << " " << Lname << endl;
    cout << "Salary: $" << Salary << endl;
}


//RESEARCHER.cpp

#include "researcher.h"
#include "Employee.h"
#include <iostream>
#include <string>


researcher::researcher(string firstName,
                       string lastName,
                       int sal,
                       string PHD, 
                       string thesis)
            : Employee(firstName,
                       lastName,
                       sal)
{
    phd = PHD;
    phdThesis = thesis;
}

researcher::researcher()
{
    phd = "PHD";
    phdThesis = "Thesis";
}

researcher::~researcher()
{

}

void researcher::print()
{
    Employee::print();
    cout << "PHD: " << phd << endl;
    cout << "Thesis: " << phdThesis << endl;
}

标签: c++classvectorpolymorphismvirtual

解决方案


推荐阅读