Problems with classes

I am making a card game. I have a class for the players hand.

Constructor:
Hand::Hand (int size)
{
card = new Card[size];
handsize = size;
elem = 0;
}


Main file:
#include <iostream>
#include <string>
using namespace std;

#include "Deck.h"
#include "Hand.h"

struct Player
{
Hand hand(4); // This declaration does not work
};

int main()
{
Hand hand(4); // This declaration works
return 0;
}


Error I get is this:
1>c:\c++ projects\projects\war\war.cpp(10): error C2059: syntax error :'constant'

I previously have a "Player" class, and encountered the same problem.

If someone could give me some advice, that would be great.
Thanks
Last edited on
You need to define the hand in the constructor of the Player with an initialization list:

1
2
3
4
5
6
7
8
9
10
11
struct Player
{
  Hand hand; // Don't call the constructor yet
  
  Player();
};

Player::Player()
  : hand ( Hand(4) ) // This is where we can specify the constructor!
{  
}


Hand hand(4);
is a function call. You're trying to create, in memory, right now, an object of type Hand.

1
2
3
4
struct Player
{
  // code here
};

is a description of a new kind of object that can be created. It is NOT code that is being run. It's just a description of a new kind of object. So it makes no sense to put a function call inside a struct. It's meaningless. When would it even get run?

I suspect you meant something like:
1
2
3
4
struct Player  // this is a new kind of object that we could make if we wanted to
{
  Hand handObject; // this new kind of object will contain a hand object
};

and then create a constructor for the struct, and in that function put how the Hand object is to be created.
Thanks for the help guys!
Topic archived. No new replies allowed.