开发者

How to make classes in NACHOS (C++)

开发者 https://www.devze.com 2023-04-07 04:47 出处:网络
I am trying to implement a player class, so I created two files in my threads folder, player.cc and player.h

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 PLA开发者_如何学PythonYER_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


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.


Did you modify the Makefile.common in the root nachos directory? I think you should add some value to THREAD_H, THREAD_O and THREAD_C.

0

精彩评论

暂无评论...
验证码 换一张
取 消