Step 4.
// test_class_Team_step4.cpp //
// here ... using ALL dynamic C strings
// and dynamic array
// AND printf from <cstdio>
//#include <iostream>
//#include <iomanip> // re. setw
//#include <string>
//#include <vector>
#include <cstdio>
#include <cstring> // re. strlen, strcpy
class MyString
{
public:
MyString( const char* s = "" ) // default and value ctors...
{
str = new char[strlen(s)+1];
strcpy( str, s );
}
~MyString() { delete [] str; } // dtor
MyString( const MyString& ms ) // copy ctor
{
str = new char[strlen(ms.str)+1];
strcpy( str, ms.str );
}
MyString& operator = ( const MyString& ms ) // overloaded =
{
if( this != &ms )
{
delete [] str;
str = new char[strlen(ms.str)+1];
strcpy( str, ms.str );
}
return *this;
}
char* get_str() const { return str; }
private:
char* str;
} ;
class Player
{
public:
// default and value ctor...
Player( MyString n = "", int i = 0 ) : name(n), id(i) {}
void print() const
{
printf( "ID: %3d, Name: %s", id, name.get_str() );
}
private:
MyString name;
int id;
} ;
class Team
{
public:
// default ctor ...
Team() : players(0), t_capacity(0), t_size(0) {}
~Team() { delete [] players; } // dtor
Team ( const Team& tm ) // copy ctor
{
t_capacity = tm.t_capacity;
t_size = tm.t_size;
players = new Player[t_capacity];
for( int i = 0; i < t_size; ++ i )
players[i] = tm.players[i];
}
Team& operator = ( const Team& tm ) // overloaded =
{
if( this != &tm )
{
delete [] players;
t_capacity = tm.t_capacity;
t_size = tm.t_size;
players = new Player[t_capacity];
for( int i = 0; i < t_size; ++ i )
players[i] = tm.players[i];
}
return *this;
}
void set_tName( MyString tN ) { tName = tN; }
//int size() const { return t_size; } // not used here
//int capacity() const { return t_capacity; } // not used here
void push_back( const Player& pl )
{
if( t_size == t_capacity ) enlarge();
players[t_size] = pl;
++ t_size;
}
void print() const
{
for( int i = 0; i < t_size; ++ i )
{
players[i].print();
putchar( '\n' );
}
printf( "Team \"%s\" has %d players.\n", tName.get_str(), t_size );
}
private:
Player* players;
int t_capacity;
int t_size;
MyString tName;
void enlarge()
{
if( t_capacity != 0 ) t_capacity += t_capacity; // double
else t_capacity = initial_capacity;
Player* old = players; // get copy of addrsss
players = new Player[t_capacity];
for( int i = 0; i < t_size; ++ i ) players[i] = old[i];
delete [] old;
}
static const int initial_capacity = 2;
} ;
int main()
{
const char* names[] = { "Brad Shaw", "Aimen Adams", "Sal Dimitry",
"Cristi Anreaz", "Poala James" };
const int ids[] = { 232, 444, 135, 52, 134 };
const int size = sizeof(ids) / sizeof(int);
const char* tName = "Toronto Maple Leafs";
Team myTeam; // calls default ctor
// get some players in the team
for( int i = 0; i < size; ++ i )
myTeam.push_back( Player( names[i], ids[i] ) );
myTeam.set_tName( tName );
myTeam.print();
}