//Employee.h #ifndef EMPLOYEE_H_ #define EMPLOYEE_H_ class Employee { public: Employee(const char * const,const char * const); ~Employee(); const char *getFirstName() const; const char *getLastName() const; static int getCount(); private: char *firstName; char *lastName; static int count; }; #endif
//Employee.cpp #include "Employee.h" #include <iostream> #include <cstring> using namespace std; int Employee::count = 0; int Employee::getCount() { return count; } Employee::Employee(const char * const first,const char * const last) { firstName = new char[strlen(first) + 1]; strcpy(firstName,first); lastName = new char[strlen(last) + 1]; strcpy(lastName,last); count++; cout << "Employee constructor for " << firstName << " " << lastName << " called." << endl; } Employee::~Employee() { cout << "~Employee() called for " << firstName << " " << lastName << endl; delete [] firstName; delete [] lastName; count--; } const char * Employee::getFirstName() const { return firstName; } const char * Employee::getLastName() const { return lastName; }
//main.cpp #include "Employee.h" #include <iostream> using namespace std; //只要测试new 和delete的用法,以及static 类成员 int main() { cout << "Number of employee before instantiation of any object is " << Employee::getCount() << endl; Employee *ePtr1 = new Employee("Susan","Banke"); cout << "Number of employees after objects are instantiated is " << ePtr1->getCount() << endl; Employee *ePtr2 = new Employee("Jax","Lanester"); cout << "Number of employees after objects are instantiated is " << ePtr2->getCount() << endl; Employee *ePtr3 = new Employee("Bob","Javin"); cout << "Number of employees after objects are instantiated is " << ePtr3->getCount() << endl; cout << "Number of all employees after objects are instantiated is " << Employee::getCount() // << ePtr1->getCount() // << (*ePtr2).getCount() // << ePtr2->getCount() // << ePtr3->getCount() //显示的结果上面全部是一样的,这就是static的用法 << endl; cout << "Employee 1:" << ePtr1->getFirstName() << " " << ePtr1->getLastName() << endl; cout << "Employee 2:" << ePtr2->getFirstName() << " " << ePtr2->getLastName() << endl; cout << "Employee 3:" << ePtr3->getFirstName() << " " << ePtr3->getLastName() << endl; delete ePtr1; ePtr1 = 0; delete ePtr2; ePtr2 = 0; delete ePtr3; ePtr3 = 0; cout << "Number of employees after objects are deleted is " << Employee::getCount() << endl;; system("pause >> cout"); return 0; }