【问题标题】:How to combine functions of a Parent-Child Class?如何结合亲子班的功能?
【发布时间】: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 个具有特定类别成员的子类。

谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

您应该了解虚拟方法。和纯虚方法。看看这个,让我知道这是否有帮助! http://www.thegeekstuff.com/2013/06/cpp-virtual-functions/ http://www.cplusplus.com/doc/tutorial/polymorphism/

【讨论】:

  • 这不是一个真正的答案,最好将其作为对该问题的评论。
  • 完美,这正是我想要的!谢谢,效果很好!
  • 我同意@callyalater 的评论。您应该通过包含专门解决 OP 问题的代码来扩展帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 2021-06-07
  • 2021-12-22
  • 2015-10-22
相关资源
最近更新 更多