gpt4 book ai didi

c++ - 从基类派生函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:39 27 4
gpt4 key购买 nike

我可能会走错路。我被要求创建一个特定类的对象数组。但是,该类有两个派生类。

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;
}

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

最佳答案

为避免切片,您需要存储指向对象的指针

Employee* data[100];

然后您可以从各种派生类创建对象并将它们放入数组中,例如

data[0] = new Salary;

为了调用正确的方法,您需要在基类中声明一个虚拟方法,然后在您的派生类中覆盖它。

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com