我收到以下错误:
指向vector.h的size()方法。使用此方法时似乎会发生这种情况:
void Player::printInventory(){
if(inventory.size() != 0){
for(unsigned int i=0; i<inventory.size(); i++){
cout<<inventory[i] << endl;
}
}
}
完整代码:
Player.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();
};
Player.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);
}
请原谅这个混乱,这段代码是从之前的代码中剔除的,这些代码有相同的错误。
答案 0 :(得分:5)
您move
unique_ptr
new Player
,以便它不再指向world.setPlayer(move(player));
...
player->printInventory();
,然后您正在使用它:
move
不要仅使用shared_ptr
来编译代码;使用{{1}},这样你就可以有多个指向对象的指针。
答案 1 :(得分:1)
使用!inventory.empty()代替inventory.size()!= 0。 因此,对于代码,当您移动unique_ptr时,unique_ptr将被释放,因此它将指向零。
答案 2 :(得分:0)
看起来你正在使用一些null对象。在崩溃之前的函数中打印此(播放器)的值。