首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何循环遍历向量fleetX和fleetY并访问"Ship“基类中的函数?

如何循环遍历向量fleetX和fleetY并访问"Ship“基类中的函数?
EN

Stack Overflow用户
提问于 2022-05-21 17:04:42
回答 1查看 23关注 0票数 -3

我想创建两个舰队,最多有9艘船,并让他们互相战斗。我的老师告诉我,我必须使用共享的指针和向量。

  • 基类:
  • 继承类:驱逐舰、巡洋舰、猎人

main.cpp

代码语言:javascript
复制
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()在我的战场类中

代码语言:javascript
复制
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;

}
EN

回答 1

Stack Overflow用户

发布于 2022-05-21 17:13:01

您正在按值传递向量,从而创建一个新副本,即不修改原始向量。

尝试通过引用传递向量

代码语言:javascript
复制
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())

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72331648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档