【发布时间】:2016-04-12 20:58:41
【问题描述】:
所以现在我必须根据“Employee”属于哪个类来调用特定的打印函数。
“Employees.cpp”中我的父类打印函数:
void Employees::printEmployee() const{
cout<<"Name: "<<employeeName<<endl;
cout<<"Salary:"<<employeeSalary<<endl;
cout<<"Employee ID: "<<employeeID<<endl;
cout<<"Employee Class: "<<employeeClass<<endl<<endl;
}
子类打印函数的一个例子是我的“Chef.cpp”打印函数:
void Chef::printChef() const{
cout<<"Name: "<<employeeName<<endl;
cout<<"Salary: $"<<calculateSalary()<<endl;
cout<<"Employee ID: "<<employeeID<<endl;
cout<<"Employee Class: "<<employeeClass<<endl;
cout<<"Share Perecent: "<<chefSharePercent<<"%"<<endl;
cout<<"Chef's Specialty: "<<chefSpecialty<<endl<<endl;
}
“Chef.cpp”的功能在“Chef.h”中定义,如下所示:
#ifndef CHEF_H_
#define CHEF_H_
#include <string>
#include "employee.h"
using namespace std;
class Chef : public Employees{
public:
Chef();
Chef(double percent, string specailty);
void setPercent(double percent);
void setSpecialty(string specailty);
double getPerecent() const;
string getSpecialty() const;
double calculateSalary() const;
void printChef() const;
private:
double chefSharePercent;
string chefSpecialty;
};
#endif
有没有什么方法可以只使用一个打印函数来打印每个类的适当成员。例如,My chef 子类具有与父“Employees”相同的所有属性,但还具有“Share Percent”和“Chef Specialty”成员。我还有另外 2 个具有特定类别成员的子类。
谢谢。
【问题讨论】:
-
Virtual function inheritance 的可能重复项。称其为骗子有点牵强,但这是您想要做的,没有必要再重复一遍。
-
更多有用信息在这里:isocpp.org/wiki/faq/virtual-functions
-
打印不应该是成员函数。
标签: c++