我想创建两个舰队,最多有9艘船,并让他们互相战斗。我的老师告诉我,我必须使用共享的指针和向量。
main.cpp
int main(int argc, const char * argv[]) {
std::vector<std::shared_ptr<Ship>> fleetX;
std::vector<std::shared_ptr<Ship>> fleetY;
Battlefield game;
game.createFleet(fleetX, fleetY);
return 0;}
createFleet()在我的战场类中
void Battlefield::createFleet(std::vector<std::shared_ptr<Ship>> fleetX, std::vector<std::shared_ptr<Ship>> fleetY) {
int hunter, destroyer, cruiser, player_Input;
// PLAYER 1
do {
cout << "BATTLEFIELD" << endl;
cout << "Player_1" << endl;
cout << "Choose the number of ships you want in your fleet (9 maximum): ";
cin >> player_Input;
} while (player_Input < 1 || player_Input > 9);
cout << endl;
do {
cout << "Choose " << player_Input << " in total ships from the following:" << endl;
cout << "HUNTER - Special Attack (Critical Hit)" << endl;
cout << "DESTROYER - Special Attack (Target Search)" << endl;
cout << "CRUISER - Special Attack (Bombardment)" << endl << endl;
cout << "HUNTER: ";
cin >> hunter;
cout << "DESTROYER: ";
cin >> destroyer;
cout << "CRUISER: ";
cin >> cruiser;
cout << endl;
} while (hunter + destroyer + cruiser != player_Input);
int iterator = 0;
while (iterator < hunter) { fleetX.push_back(std::shared_ptr<Ship>(new Hunter())); iterator++;} iterator = 0;
while (iterator < destroyer) { fleetX.push_back(std::shared_ptr<Ship>(new Destroyer())); iterator++;} iterator = 0;
while (iterator < cruiser) { fleetX.push_back(std::shared_ptr<Ship>(new Cruiser())); iterator++;} iterator = 0;
}发布于 2022-05-21 17:13:01
您正在按值传递向量,从而创建一个新副本,即不修改原始向量。
尝试通过引用传递向量
void Battlefield::createFleet(
std::vector<std::shared_ptr<Ship>>& fleetX,
std::vector<std::shared_ptr<Ship>>& fleetY
) {
// rest of code
}编辑:
使用std::make_shared<Hunter>()而不是std::shared_ptr(new Hunter())
https://stackoverflow.com/questions/72331648
复制相似问题