//6. Статични членове на клас - данни и функции. // // EMPLOY1.H // An employee class #ifndef EMPLOY1_H #define EMPLOY1_H class Employee { public: Employee(const char*, const char*); // constructor ~Employee(); // destructor char *getFirstName() const; // return first name char *getLastName() const; // return last name // static member function static int getCount(); // return # objects instantiated private: char *firstName; char *lastName; // static data member static int count; // number of objects instantiated }; #endif ------ // EMPLOY1.CPP // Member functions definitions for class Employee #include #include #include #include "employ1.h" // Initialize the static data member int Employee::count = 0; // Define the static member function that // returns the number of employee objects instantiated. int Employee::getCount() { return count; } // Constructor dynamically allocates space for the // first and last name and uses strcpy to copy // the first and last names into the object Employee::Employee(const char *first, const char *last) { firstName = new char[ strlen(first) + 1 ]; assert(firstName != 0); // ensure memory allocated strcpy(firstName, first); lastName = new char[ strlen(last) + 1 ]; assert(lastName != 0); // ensure memory allocated strcpy(lastName, last); ++count; // increment static count of employees cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; } // Destructor deallocates dynamically allocated memory Employee::~Employee() { cout << "~Employee() called for " << firstName << ' ' << lastName << endl; delete firstName; // recapture memory delete lastName; // recapture memory --count; // decrement static count of employees } // Return first name of employee char *Employee::getFirstName() const { char *tempPtr = new char[strlen(firstName) + 1]; assert(tempPtr != 0); // ensure memory allocated strcpy(tempPtr, firstName); return tempPtr; } // Return last name of employee char *Employee::getLastName() const { char *tempPtr = new char[strlen(lastName) + 1]; assert(tempPtr != 0); // ensure memory allocated strcpy(tempPtr, lastName); return tempPtr; } ------------- // FIG7_9.CPP // Driver to test the employee class #include #include "employ1.h" main() { cout << "Number of employees before instantiation is " << Employee::getCount() << endl; // use class name Employee *e1Ptr = new Employee("Susan", "Baker"); Employee *e2Ptr = new Employee("Robert", "Jones"); cout << "Number of employees after instantiation is " << e1Ptr->getCount() << endl; cout << endl << "Employee 1: " << e1Ptr->getFirstName() << " " << e1Ptr->getLastName() << endl << "Employee 2: " << e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << endl << endl; delete e1Ptr; // recapture memory delete e2Ptr; // recapture memory cout << "Number of employees after deletion is " << Employee::getCount() << endl; return 0; } -------------------------------------------------------