我收到以下错误:
- TBG.exe 中 0x012a4bd9 处的未处理异常:0xC0000005:访问冲突读取位置 0x0000002c。
指向vector.h的size()方法。使用此方法时似乎会发生:
void Player::printInventory(){
if(inventory.size() != 0){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
完整代码:
播放器.h:
#pragma once
#include <vector>
#include <memory>
using namespace std;
class Player
{
private:
int health;
string name;
vector<int> inventory;
public:
Player(void);
Player(string);
~Player(void);
void changeHealth(int);
void addToInventory(int);
void removeFromInventory(int);
void printInventory();
};
播放器.cpp:
#include "Player.h"
#include <iostream>
#include <string.h>
Player::Player(void)
{
health = 20;
}
Player::Player(string newName)
{
name = newName;
health = 20;
}
Player::~Player(void)
{
}
void Player::changeHealth(int amount){
health += amount;
}
/*void Player::addToInventory(int item){
inventory.push_back(item);
}
void Player::removeFromInventory(int itemID){
for(unsigned int i=0; i<inventory.size(); i++){
if(inventory[i] == itemID)
inventory.erase(inventory.begin()+i);
}
}*/
void Player::printInventory(){
if(!inventory.empty()){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
主要的:
#include "World.h"
#include "Player.h"
#include <iostream>
#include <memory>
World world;
void main(){
unique_ptr<Player> player(new Player("Ted"));
world.setPlayer(move(player));
int selection = 0, inventoryOption = 0, exitOption = 0;
do{
inventoryOption = 0;
exitOption = inventoryOption + 1;
cout<< inventoryOption <<". View Inventory"<<endl;
cout<< exitOption <<". Quit game";
cin>>selection;
if(selection == inventoryOption){
player->printInventory();
}
else{
}
}while(selection != exitOption);
}
请原谅混乱,此代码是从具有相同错误的先前代码中删除的。