"读取访问冲突:这是nullptr"以为我正确分配了它......?

时间:2016-05-02 03:30:26

标签: c++ function class pointers nullreferenceexception

我有一个播放器类,其中包含播放器的名称,正确的答案以及播放器获得的错误答案。当我尝试访问getRight(),getWrong(),addToRight()或addToWrong()函数时,我收到一条错误,上面写着"读取访问冲突:这是nullptr"在这些职能内部的陈述中。我一定不能正确设置我的指针。我应该做些什么改变?谢谢!

这是Player.h文件

#ifndef PLAYER_H
#define PLAYER_H
#pragma once

using namespace std;
class Player;//FWD declaration

class Player
{
public:
    Player();
    Player(string playerName);

    string getName() const
    {
        return name;
    }

    //These functions show stats from
    //current round
    int getRight() const
    {
        return right;
    }

    int getWrong() const
    {
        return wrong;
    }

   //These functions update
   //player info that will be saved
   //to player profile
   void setName(string userName);
   void addToRight();
   void addToWrong();

private:
     string name;
     int right;
     int wrong;
};
#endif

这是Player.cpp文件:

#include <iostream>
#include <iomanip>
#include <fstream>
#include "Player.h"

using namespace std;

Player::Player()
{
    name = "";
    right = 0;
    wrong = 0;
}

Player::Player(string playerName)
{
    ifstream inFile;
    ofstream outFile;
    string name = playerName;
    string fileName = playerName + ".txt";

    inFile.open(fileName.c_str());
    if (inFile.fail())
    {
        outFile.open(fileName.c_str());
        outFile << 0 << endl;
        outFile << 0 << endl;
        outFile.close();
        inFile.close();
        setName(playerName);
        right = 0;
        wrong = 0;

        cout << "Welcome new player!"
            << " Your statistics profile has been created." << endl;
    }
    else
    {
        inFile >> right;
        inFile >> wrong;
        inFile.close();
        setName(playerName);
        cout << "Welcome back!" << endl;
    }
}

void Player::setName(string userName)
{
    name = userName;
}

void Player::addToRight()
{
    right = right + 1;
}

void Player::addToWrong()
{
    wrong = wrong + 1;
}

以下是我的主要内容:

#include <iostream>
#include <string>
#include "Player.h"

using namespace std;

void test(Player *player);

int main()
{
    Player *player = nullptr;


    test(player);

    cout << "name: " << player->getName() << endl;
    cout << "right: " << player->getRight() << endl;

    player->addToRight();

    cout << "right: " << player->getRight() << endl;

    return 0;
}

void test(Player *player)
{
    string name;

    cout << "name: ";
    getline(cin, name);
    player = new Player(name);
}

在处理指针以避免这些访问冲突时,是否必须以不同方式设置类?谢谢!

1 个答案:

答案 0 :(得分:6)

void test(Player *player) {
    ...
    player = new Player(...);
}

这只会改变播放器的本地副本。要更改函数外部的指针,需要引用指针(或双指针)。使用:

void test(Player *& player) {...}

代替。