gpt4 book ai didi

c++ - 将指向对象数组的指针传递给函数

转载 作者:行者123 更新时间:2023-11-30 05:36:22 25 4
gpt4 key购买 nike

当我运行这段代码时,它崩溃了,没有任何错误。我已经尝试了我所知道的一切并进行了搜索,但我可以解决这个问题。它构建并运行良好,并一直到 FleetCapacity 中的 cout 并且关于该行的某些内容正在使代码崩溃。当我注释掉那行代码时,代码运行良好,所以我不确定为什么那行代码导致我的程序崩溃和烧毁。

#include <iostream>
#include <string>
using namespace std;

class Ship{
private:
string shipName;
string shipYear;
public:
Ship(string sN,string sY){shipName=sN; shipYear=sY;}
virtual void printInfo();
void setShipName(string);
virtual string getShipName();
void setShipYear(string);
string getShipYear();
};

class CruiseShip:public Ship{
private:
int maxPass;
int maxCrew;
public:
CruiseShip(string sN,string sY, int mP,int mC):Ship(sN,sY){setShipName(sN);maxPass=mP; maxCrew=mC; }
void printInfo();
void setMaxPass(int);
int getMaxPass();
void setMaxCrew(int);
int getMaxCrew();
};

class CargoShip:public Ship{
private:
int cargoCap;
public:
CargoShip(string sN,string sY,int cC):Ship(sN,sY){setShipName(sN);cargoCap=cC;}
void printInfo();
void setCargoCap(int);
int getCargoCap();

};


void Ship::setShipName(string sN){shipName=sN;}
string Ship::getShipName(){return shipName;}
void Ship::setShipYear(string sN){shipYear=sN;}
string Ship::getShipYear(){return shipYear;}
void Ship::printInfo(){
cout<<"The ships name is "<<shipName<<endl;
cout<<"The ships year is "<<shipYear<<endl;
}

void CruiseShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships maximum passangers is "<<maxPass<<endl;
}
void CruiseShip::setMaxPass(int mP){maxPass=mP;}
int CruiseShip::getMaxPass(){return maxPass;}
void CruiseShip::setMaxCrew(int mC){maxCrew=mC;}
int CruiseShip::getMaxCrew(){return maxCrew;}

void CargoShip::printInfo(){
cout<<"The ships name is "<<getShipName()<<endl;
cout<<"The ships cargo capacity is "<<cargoCap<<endl;
}
int CargoShip::getCargoCap(){return cargoCap;}
void CargoShip::setCargoCap(int cC){cargoCap=cC;}




void fleetCapacity(Ship** s ,int e){

cout << "Name of ship: " << s[e]->getShipName() << endl;


}

int main()
{
const int NUMSHIPS = 3;
//int aSize = NUMSHIPS;
// array of ship pointers initialized with addresses of dynamically allocated class objects.
Ship *ships[NUMSHIPS] = {
new Ship("The Dinghy Berry", "1982"),
new CruiseShip("Disney Adventure Tours"," ",500,100),
new CargoShip("The Sea Trucker"," ", 50)

};

for (int i = 0; i < NUMSHIPS; i++ )
{
ships[i]->printInfo();
}

cout << "The entire fleet capacity is: ";
fleetCapacity(ships, NUMSHIPS);
cout << " tons." << endl;
return 0;
}

最佳答案

您正在调用 fleetCapacity(ships, NUMSHIPS); 然后访问 s[e] (ships[NUMSHIPS])功能。有效索引为 0NUMSHIPS-1

关于c++ - 将指向对象数组的指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33600971/

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