Search code examples
c++classnachos

How to make classes in NACHOS (C++)


I am trying to implement a player class, so I created two files in my threads folder, player.cc and player.h

player.h goes like this :

#ifndef PLAYER_H
#define PLAYER_H
#include "utility.h"

class Player()
{
  public:
   //getPlayerID();
};

#endif

then player.cc goes like

#include "player.h"

class Player()
{
  string playerID;
  int timeCycle;
}

Then in my main.cc and threadtest.cc , I add in #include player.h and then I start to errors and it fails to compile. I am new to nachos and a little bit unfamiliar with c++, so I am confused as to how to resolve this problem. Nachos does not provide a solution through the compiler either.

When I type gmake, it says two things for errors. 1. parse error before '(' in player.h (referring to Player()) 2. * [main.o] Error 1


Solution

  • Let's go through line-by-line:

    #ifndef PLAYER_H
    #define PLAYER_H
    #include "utility.h"
    

    So far so good, you might check if your compiler supports #pragma once, but the macro will work perfectly fine.

    class Player()
    

    () aren't allowed in a class name, take them off

    {
      public:
       //getPlayerID();
    };
    
    #endif
    

    The rest of the header file is ok. Let's look at the implementation file:

    #include "player.h"
    

    Perfect. Putting a class in a header is the best way to make sure you only have one definition used in your whole program.

    class Player()
    

    Parentheses aren't allowed, but here you have a bigger problem. You already have a class with that name. Let the header provide the class definition, the implementation file just needs to provide the non-inline member functions (and any helper code).

    {
      string playerID;
      int timeCycle;
    }
    

    Here's a complete corrected version:

    #if !defined(PLAYER_H)
    #define PLAYER_H
    
    #include <string>
    #include "utility.h"
    
    class Player
    {
         std::string player_id;
         int time_cycle;
    
    public:
         // this is how you make a constructor, the parenthesis belong here, not on the class name
         Player(std::string id, int time);
    
         std::string getPlayerId() const;
    };
    
    #endif /* !defined(PLAYER_H) */
    

    and implementation file

    #include "player.h"
    
    // and this is how you write a non-inline constructor
    Player::Player(std::string id, int time)
        : player_id(id)
        , time_cycle(time)
    {}
    
    std::string Player::getPlayerId() const
    {
        return player_id;
    }
    

    All of these problems are really basic C++ stuff, nothing to do with NachOS.