_curLevel.size()是我在类级别创建的私有向量,每当我尝试在getPosition函数中运行.size()函数时,它返回0。但是在其他函数中,此命令运行良好并返回13。因此,我的for循环无法正常工作。 我也复制了main.cpp和level.h。
level.cpp
bool level::loadGame(string file_name){
string line;
load.open(file_name);
if (load.fail()){
cout << "Failed to Load Saved Game" << endl;
return false;
}else{
while ((getline(load, line))){
_curLevel.push_back(line);
}
cout << _curLevel.size() << endl;
return true;
}
}
int level::getPosition(char object,char coor){
char a;
cout << _curLevel.size() << endl;
for (unsigned int y = 0; y < (_curLevel.size()); y++){
for (unsigned int x = 0; x < (_curLevel[y].size()); x++){
a = _curLevel[y][x];
if (object == a){
switch (coor){
case 'x':
return x;
case 'y':
return y;
default:
return 1;
}
}
}
}
return 1;
}
void level::printLevel(){
for (unsigned int i = 0; i < (_curLevel.size()); i++){
cout << _curLevel[i] << endl;
}
cout << _curLevel.size() << endl;
}
level.h
#pragma once
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class level
{
public:
level();
bool loadGame(string file_name);
int getPosition(char object, char coor);
/*void saveGame(string file_name);*/
void printLevel();
void initLevel();
private:
vector <string> _curLevel;
ifstream load;
ofstream save;
};
main.cpp
#include <iostream>
#include "level.h"
#include "player.h"
using namespace std;
int main(){
level level;
level.loadGame("ha.txt");
level.printLevel();
player player;
system("pause");
return 0;
}
player.cpp
#include "player.h"
#include "global.h"
#include <iostream>
#include "level.h"
using namespace std;
player::player()
{
level level;
_playeryCoor = level.getPosition(playersymbol,'y');
_playerxCoor = level.getPosition(playersymbol,'x');
cout << _playeryCoor << endl;
cout << _playerxCoor << endl;
cout << "e";
}
player.h
#pragma once
#include "level.h"
#include <iostream>
class player
{
public:
player();
private:
int _playeryCoor;
int _playerxCoor;
};
global.h
namespace
{
char playersymbol = '@';
}
ha.txt
####################################
#..................................#
#..................................#
#..................................#
#..................................#
#...............@..................#
#..................................#
#..................................#
#..................................#
#..................................#
#..................................#
#..................................#
####################################
答案 0 :(得分:0)
错误在于添加的player
代码中:您在level
的构造函数中声明了本地player
。该本地vector
中的level
未填充,因此其大小为零。
一种可行的解决方案是将全局level
作为参数传递给player
的构造函数。