我可能正在以这种错误的方式。我被要求创建一个特定类的对象数组。但是,该类具有两个派生类。

class Employee {
     // Some stuff here about the backbone of the Employee class
}

class Salary: public Employee {
     // Manipulation for Salary employee
}

class Hourly: public Employee {
     // Manipulation for hourly Employee
}

// Main Program
int main (int argc, char**argv) {

Employee data[100]; // Creates an array of Employee objects

while (employeecount > 100 || employeecount < 1) {
    cout << "How many employees? ";
    cin >> employeecount;
}

for(int x = 0; x <= employeecount; x++) {

    while (status != "S" || status != "s"|| status != "H" || status != "h") {
        cout << "Employee Wage Class (enter H for hourly or S for Salary)";
        cin >> status;
    }


    if (status == "S" || status == "s") { // Salaried Employee
        new
    } else { // We valid for hourly or salary, so if its not Salaried it's an hourly

    }

}

     return 0;
}

我想问的问题是,基类可以调用派生类的方法吗?例如,如果我为Salary类创建了一个名为getgross的方法:我可以调用这样的方法:Employee.getgross()吗?如果没有,如何调用子类方法?

最佳答案

getgross()类中将virtual声明为Employee

例:

class Employee {
     virtual int getgross();
}

class Salary: public Employee {
     virtual int getgross();
}

每当在指向getgross()对象的Employee*上调用Salary时,就会调用getgross()Salary
我也添加了virtualSalary::getgross()中,目前不需要,但是最好现在包括它,因为您以后可能想要派生一个类形式Salary

该数组必须是一个指针数组,以避免slicing problem。更好的方法是使用智能指针的vector

关于c++ - 从基类派生函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32653632/

10-09 02:59