Created
February 17, 2018 09:41
-
-
Save jnovikov/c324539df3f7668659785cb6d311c46d to your computer and use it in GitHub Desktop.
Constructor and destructor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
using namespace std; | |
class Student { | |
private: | |
char name[51]; | |
char surname[51]; | |
int *marks; | |
int marks_counter; | |
int hp; // очки здоровья персонажа | |
int energy; | |
void change_field(int &field, int delta); | |
public: | |
bool is_alive(); | |
void show(); | |
void eat(); | |
void wait(); | |
void setMark(int mark); | |
Student(); // Конструктор | |
Student(int hp,int energy=100); | |
~Student(); // Деструктор | |
}; | |
// Конструктор по умолчанию(без параметров) | |
Student::Student() { | |
cin >> this->name >> this->surname; | |
this->hp = 100; | |
this->energy = 100; | |
this->marks_counter = 0; | |
this->marks = new int[100]; | |
} | |
Student::Student(int hp, int energy) { | |
cin >> this->name >> this->surname; | |
this->hp = hp; | |
this->energy = energy; | |
this->marks_counter = 0; | |
this->marks = new int[100]; | |
} | |
Student::~Student() { | |
delete [] this->marks; | |
} | |
void Student::change_field(int &field, int delta) { | |
field += delta; | |
if (field > 100) { | |
field = 100; | |
} | |
if (field < 0) { | |
field = 0; | |
} | |
} | |
bool Student::is_alive() { | |
return this->hp > 0; | |
} | |
void Student::show() { | |
cout << this->name << " " << this->surname << ": "; | |
// setw(3) -- не менее 3 знаков в выводе | |
// setfill('0') -- если знаков меньше 3, добавить ноль слева | |
cout << "HP = " << setw(3) << setfill('0') << hp << ", "; | |
cout << "Energy = " << setw(3) << setfill('0') << energy << ". "; | |
if (!is_alive()) { | |
cout << "Game over."; | |
} | |
cout << endl; | |
cout << "Marks: "; | |
for (int i = 0; i < this->marks_counter;i++) { | |
cout << this->marks[i] << " "; | |
} | |
cout << endl; | |
} | |
void Student::eat() { | |
if (is_alive()) { | |
change_field(energy,7); | |
change_field(hp,1); | |
} | |
} | |
void Student::wait() { | |
if (is_alive()) { | |
change_field(energy,-3); | |
change_field(hp,1); | |
} | |
} | |
void Student::setMark(int mark) { | |
this->marks[this->marks_counter] = mark; | |
this->marks_counter++; | |
} | |
int main() { | |
Student *s = new Student(100,100); | |
Student k(5,50); | |
k.show(); | |
s->setMark(3); | |
s->setMark(5); | |
s->show(); | |
delete s; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment