我对使用C ++并开发一个简单的战舰游戏还是比较陌生的。我有一个函数,可以通过接收船对象矢量来初始化船的类型和长度。我已经确认类型和船长在函数内部正在更新,但更改未持久存在于主函数中。任何帮助将不胜感激。
#include <iostream>
#include <vector>
#include "ships.h"
#include "board.h"
#include "player.h"
using std::vector;
void initialize_ships(vector<ship> &newFleet)
{
vector<string> ship_types = { "carrier","battleship","submarine","cruiser","destroyer" };
for (auto ii = 0; ii != newFleet.size(); ++ii)
{
newFleet[ii].type = ship_types[ii];
newFleet[ii].setLength();
if (newFleet[ii].type == "carrier")
{
std::cout << "Carrier in function has type: " << newFleet[ii].type << std::endl;
}
}
}
int main()
{
ship player_carrier, player_battleship, player_submarine, player_cruiser, player_destroyer;
vector<ship> player_fleet = {player_carrier, player_battleship, player_submarine, player_cruiser, player_destroyer };
initialize_ships(player_fleet);
std::cout << "Carrier in main has type: " << player_carrier.type << std::endl;
system("pause");
return 0;
}
#ifndef SHIPS_H
#define SHIPS_H
#include <iostream>
#include <string>
using std::string;
struct ship
{
// ships member variables
int len;
char dir;
int health;
int row;
int col;
char symb;
string type;
void setLength()
{
if (type == "carrier")
{
len = 5;
}
else if (type == "battleship")
{
len = 4;
}
else if (type == "cruiser")
{
len = 3;
}
else if (type == "submarine")
{
len = 3;
}
else if (type == "destroyer")
{
len = 2;
}
else
{
std::cout << "Invalid ship type!" << std::endl;
}
}
};
#endif // SHIPS_H
答案 0 :(得分:0)
不小心制作副本是更改“丢失”的常见原因。对于这种特殊情况,要在容器中容纳对象并且为这些对象命名(就像它们是类的成员一样),明智的做法是进行引用到容器中的对象:
vector<ship> player_fleet(5);
ship &player_carrier=player_fleet[0],
&player_battleship=player_fleet[1],
&player_submarine=player_fleet[2],
&player_cruiser=player_fleet[3],
&player_destroyer=player_fleet[4];
请注意不要使vector
重新分配,因为那样会使您的引用无效。 (当然,如果它永远不会改变大小,则ship player_fleet[5];
就足够了。)