c++ - 虚函数和向量(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;
}
解决方案
推荐阅读
- eloquent - 从视图中的where子句获取关系数据
- python - BeautifulSoup 错误:列表索引超出范围
- php - 带有 Ajax 表单提交的 Laravel 5 `Internal Server Error` (500)
- android - 从覆盖函数获取数据
- c# - C# FileStream.Read 不读取最后一个块
- php - php图像和文本上传不起作用
- matlab - 使用 cellfun 对集群进行回归时出错
- windows - 构建规则中的 Bazel 环境变量
- html - Safari 11.3.1 状态栏白底白字
- mysql - SQL 查询 - 从以逗号分隔的一列中获取数据并按行显示