0

次のエラーが発生します。

  • 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;
        }
    }
}

完全なコード:

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);

}

混乱を許してください、このコードは同じエラーを持っている前のコードから虐待されています。

4

3 に答える 3

5

あなたはそれがもはやをmove指さないようにそれを使っています、そしてあなたはそれを使っています:unique_ptrnew Player

world.setPlayer(move(player));

...

player->printInventory();

moveコードをコンパイルするためだけに使用しないでください。shared_ptrオブジェクトへの複数のポインタを持つことができるように使用します。

于 2012-07-13T22:51:35.080 に答える
1

代わりに!inventory.empty()を使用します。inventory.size()!= 0。したがって、コードの場合、unique_ptrを移動すると、unique_ptrが解放されるため、ゼロを指します。

于 2012-07-13T22:41:37.570 に答える
0

nullオブジェクトを使用しているようです。クラッシュ直前の関数にthis(Player)の値を出力します。

于 2012-07-13T22:51:54.090 に答える