我目前正在做家庭作业,我们使用void函数来打印信息。
我们的老师希望我们这样做:
在具有Ship Array的程序中演示该类。分配 各种Ship,CruiseShip和CargoShip对象到数组元素。 然后程序应该遍历数组,调用对象 printInfo方法。“
Ship ob1; // object of ship class CruiseShip ob2; // object of
cruiseship class CargoShip ob3; // object of cargoship class
typedef void((*shipArray)()); // declaring
void(*ob1)() = ob1.printInfo; // pointer to print info function in
ship class void(*ob2)() = ob2.printInfo; // pointer to print info
function in cruiseship class void(*ob3)() = ob3.printInfo; // pointer
to print info function in cargoship class
shipArray ship[3] = {ob1.printInfo, ob2.printInfo, ob3.printInfo}; //
array assigns the functions to each
element
for (int i = 0; i < 3; i++) // loop to output each function {
cout << ship[i] << endl << endl; }
我如何做到这一点?我被卡住了......
答案 0 :(得分:1)
指令说数组应包含船只,而不是函数指针。但是,为了避免对象切片,它需要是一个指针数组。你需要:
Ship *ships[] = {&obj1, &obj2, &obj3};
for (int i = 0; i < sizeof(ships)/sizeof(*ships); i++) {
ship[i]->printInfo();
}
答案 1 :(得分:0)
您没有在数组中调用函数。
for (int i = 0; i < 3; i++) // loop to output each function
{
cout << ship[i]() << endl << endl;
}