"读访问违规:这是nullptr"我以为我正确分配了它?

Van*_*our 1 c++ pointers class function 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
Run Code Online (Sandbox Code Playgroud)

这是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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要内容:

#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);
}
Run Code Online (Sandbox Code Playgroud)

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

xax*_*xon 6

void test(Player *player) {
    ...
    player = new Player(...);
}
Run Code Online (Sandbox Code Playgroud)

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

void test(Player *& player) {...}
Run Code Online (Sandbox Code Playgroud)

代替.