TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: JASON REYNOLDS
from: CLIFF RHODES
date: 1997-03-16 22:11:00
subject: Help with Classes

--> Jason Reynolds wrote to All  <--
 
JR>I would like to know how to store and retrieve
JR>char's.  I've been unable to use char's in a class.  Could
JR>someone please help me out?
 
Jason, I would assume you are interested in arrays of chars rather than
single chars. If you have a newer compiler, you can use the C++ String
class. Look for it in your documentation. If you don't have it, you can
do something like the following:
 
#include 
#include 
 
class PlayerInfo
{
  public:
    // Add these to support array of chars
    PlayerInfo()  { itsStr = 0; }  // Set pointer to 0
    ~PlayerInfo() { if(itsStr) delete [] itsStr; } // Free mem
 
    int  GetHitPoint() const { return itsHitPoint;}
    void SetHitPoint(int hitPoint) { itsHitPoint = hitPoint; }
 
    // For single chars
    char GetPlayerChar(void) const { return itsChar; }
    void SetPlayerChar(char c) { itsChar = c; }
 
    // For array of chars
    const char const * GetPlayerStr(void) const { return itsStr; }
    void SetPlayerStr(const char *s) {
             if(itsStr) delete [] itsStr;      // If used, free it
             itsStr = new char[strlen(s) + 1]; // Get new memory
             strcpy(itsStr, s);  }             // Copy the string
 
  private:
    int itsHitPoint;                    // characters Hit Points
    char itsChar;   // Single char
    char *itsStr;   // Pointer to array of chars
};
 
int main(void)
{
  PlayerInfo Player;
 
  Player.SetHitPoint(40);
  Player.SetPlayerChar('A');
  Player.SetPlayerStr("Jason Reynolds");
 
  cout << "Hit Points: " << Player.GetHitPoint() << endl;
  cout << "Player char: " << Player.GetPlayerChar() << endl;
  cout << "Player name: " << Player.GetPlayerStr() << endl;
 
  return 0;
}
 
X CMPQwk 1.42 1692 X"As to the adjective: when in doubt, strike it out."
--- Maximus/2 3.01
---------------
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.