1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <iostream>
#include <string>
using namespace std;
class Game
{
public:
static int countObj;
explicit Game(char* title = "Default title", int difficulty = 10, int players = 4)
{
delete [] mp_title;
mp_title = new char[strlen(title) + 1];
strcpy_s(mp_title, strlen(title) + 1, title);
m_difficulty = difficulty;
m_players = players;
m_objID = countObj;
cout << "Object " << ++countObj << " created" << endl;
}
Game(const Game& objGame)
{
delete [] mp_title;
mp_title = new char[strlen(objGame.mp_title) + 1];
strcpy_s(mp_title, strlen(objGame.mp_title) + 1, objGame.mp_title);
m_difficulty = objGame.m_difficulty;
m_players = objGame.m_players;
cout << "Object " << ++countObj << " created using copy constructor" << endl;
m_objID = countObj;
}
~Game()
{
cout << "Destructor called on object: " << this->getObjID() << endl;
delete [] mp_title;
}
Game operator=(const Game&& objGame)
{
cout << "= operator used as rh expression on object: " << this->getObjID() << endl;
delete [] mp_title;
mp_title = new char[strlen(objGame.mp_title) + 1];
strcpy_s(this->mp_title, strlen(objGame.mp_title) + 1, objGame.mp_title);
return *this;
}
Game& operator=(const Game& objGame)
{
if (this != &objGame)
{
cout << "= operator called on object " << this->getObjID() << endl;
delete [] mp_title;
size_t len = strlen(objGame.mp_title) + 1;
mp_title = new char[len];
strcpy_s(mp_title, len, objGame.mp_title);
m_difficulty = objGame.m_difficulty;
m_players = objGame.m_players;
}
return *this;
}
Game operator+(const Game& objGame) const
{
cout << "+ called" << endl;
return Game("Default title",
(m_difficulty + objGame.m_difficulty),
(m_players + objGame.m_players) );
}
char* getTitle() { return mp_title; }
void setTitle(char* title) { mp_title = title; }
int getObjID() { return m_objID; }
private:
char* mp_title;
int m_difficulty;
int m_players;
int m_objID;
};
int Game::countObj = 0;
int main()
{
Game game1("Game 1", 10, 4);
Game game2("Game 2", 5, 2);
Game game3 = game2;
game2.operator=(game3.operator+(game1));
cout << game1.getObjID() << endl << game2.getObjID() << endl;
cout << game1.getTitle() << endl << game2.getTitle() << endl;
return 0;
}
|