What is causing my error? I am trying to create a player class and store a players name as a variable

StackOverflow https://stackoverflow.com/questions/15808632

Domanda

another noob here, so I hope someone with a bit of sense can help me! As my question states, I am simply trying to create a player class (it is for an RPG game). However, I have tried multiple ways of doing this, with the code shown being the latest, however I keep coming across different errors. I am using Microsoft visual c++ 2010 express and the error that I am currently facing is:

1>player.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string,class std::allocator > Player::m_playerName" (?m_playerName@Player@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)

I hope this is enough detail! The rest of the code/files I have created are as follows:

game.cpp

#include <iostream>
#include "player.h"

using namespace std;



int main() 
{

    Player main;


   main.setStats(); 
   main.showStats();


    int stopper;
   cin >> stopper;

    return 0;



}

player.h

#include <string>

class Player
    {
    public:

        Player();
        void showStats();
        void setStats();        


    private: 

         int m_playerLVL;
         static std::string m_playerName;
    };

player.cpp

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

using namespace std; 

Player::Player()
{
    cout << "Please enter your name: ";
    string playerName;
    getline (cin, playerName);
    m_playerName = playerName;
}

    void Player::showStats()
    {
        cout << "Hello, i am " << m_playerName << "and i am lvl " << m_playerLVL; 
    }

    void Player::setStats()
    {
        m_playerLVL = 1;
    }
È stato utile?

Soluzione

You are declaring the name of the player to be static:

static std::string m_playerName; // DON'T MAKE IT STATIC!

That's semantically incorrect, and removing static happens to solve your problem. Each instance of Player should associate a different value to m_playerName (because each player has their own name). Declaring a data member static makes it global for the whole Player class (i.e. it is not given a per-instance value, but one global value which is the same for all Player objects). That doesn't sound like something you would want.


Now if for any reason you really meant to declare this as a static data member, then you should provide a definition for it at the global namespace scope:

std::string Player::m_playerName;

The linker is complaining about the lack of such a definition.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top