简体   繁体   中英

Access private data members from within another class

I have a player class. In the class I have a hand of size three, which is of type card. Card is another class. I am trying to access the private data members of hand through class, but inside the player class. This is the error I get:

scat.cpp: In member function ‘void player::setHand(card*)’:
scat.cpp:117:10: error: request for member ‘cardCopy’ in     
‘((player*)this)->player::hand’, which is of pointer 
type ‘card*’ (maybe you meant to use ‘->’ ?)hand.cardCopy(c);

#include <iostream>
using namespace std;

class card{
    char *suit;
    char *rank;
    int cvalue;
    char *location;

public:
    card::cardCopy(card *c);
};
class player{

card *hand;
public:
    player::setHand(card *c);
};
void card::cardCopy(card *c)
{
  strcopy(rank, (*c).rank);
  strcopy(suit, (*c).suit);
  strcopy(location, (*c).location);
  cvalue = (*c).cvalue;
}
player::player()
   {
    name = new char[20];
    hand = new card[3];
}

void player::setHand(card*c)
  {
    hand.cardCopy(c);
  }

I dont understand why i cant access the function cardCopy like this..hand is a card type!!!

since your "hand" is a pointer you have to use -> operator to access member variables and functions

class player{
 card *hand // member pointer of card type
}

void player::setHand(card *c)
{
  hand->cardCopy(c);
}

Well, there are several problems with your code that i can see:

  • In you class declaration, you are declaring functions without specifying a return type.

  • *hand does not have a type in its declaration.

  • hand is a pointer, so you need to use the -> operator to access its members.

  • hand is being initialized to an array of length 3 in the constructor, yet you are not specifying which element you are trying to access.

Try this:

#include <iostream>
#define strcopy(a,b) *a=*b
using namespace std;

class card
{
private:
    char *suit;
    char *rank;
    int cvalue;
    char *location;
public:
    void cardCopy(card *c);
};

class player
{
private:
    char *name;
    card *hand;
public:
    player();
    void setHand(card *c);
};

void card::cardCopy(card *c)
{
  strcopy(rank, c->rank);
  strcopy(suit, c->suit);
  strcopy(location, c->location);
  cvalue = c->cvalue;
}

player::player()
{
    name = new char[20];
    hand = new card[3];
}

void player::setHand(card*c)
{
    hand[0].cardCopy(c);
}

Of course, you will also need to provide an implementation of strcopy() within this scope in order for this to work. I have provided one for convenience, but i can not be sure that my implementation will do exactly what you want it to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM