Code /* * person2.cpp * CIS 250 * David Klick * 2005-02-21 * 2010-10-13 modified to add corrections * * Demonstration of friends, copy constructor, * and operator overloading. */ #include "person2.h" int person2::count = 0; person2::person2() { init("", 0L, 'M', 0); } person2::person2(const char* name, const long ssn, const char gender, const int age) { init(name, ssn, gender, age); } person2::person2(const person2& p) { init(p.name, p.ssn, p.gender, p.age); } void person2::init(const char* nm, const long ssn, const char gender, const int age) { name = NULL; setName(nm); setSSN(ssn); setGender(gender); setAge(age); count++; } person2::~person2() { if (name != NULL) delete[] name; count--; } void person2::setName(const char* nm) { if (name != NULL) delete[] name; if (nm == NULL) { name = new char[1]; if (name != NULL) name[0] = '\0'; } else { name = new char[strlen(nm) + 1]; if (name != NULL) strcpy(name, nm); } } void person2::setSSN(const long ssn) { // you may have to use the this pointer if // arg names match instance variable names if (ssn < 0L) this->ssn = 0L; else this->ssn = ssn; } void person2::setGender(const char g) { if (g=='M' || g=='m') gender = 'M'; else gender = 'F'; } void person2::setAge(const int age) { // you may have to use the this pointer if // arg names match instance variable names if (age < MINIMUM_AGE) this->age = MINIMUM_AGE; else if (age > MAXIMUM_AGE) this->age = MAXIMUM_AGE; else this->age = age; } const char* person2::getName() const { return name; } long person2::getSSN() const { return ssn; } int person2::getAge() const { return age; } char person2::getGender() const { return gender; } int person2::getCount() { return count; } person2& person2::operator=(const person2& p) { if (this != &p) { setName(p.name); setSSN(p.ssn); setGender(p.gender); setAge(p.age); } return *this; } bool person2::operator==(const person2& p) const { return strcmp(name, p.name)==0 && age==p.age && gender==p.gender && ssn==p.ssn; } ostream& operator<<(ostream& strm, const person2& p) { strm << "Name: " << p.name << " (" << p.gender << ")" << "\n SSN: " << p.ssn << "\n Age: " << p.age << '\n'; return strm; } istream& operator>>(istream& strm, person2& p) { char tmpName[40]; int tmpAge; long tmpSSN; char tmpGender; cout << "Enter name: "; strm.getline(tmpName, 40, '\n'); cout << "Enter SSN: "; strm >> tmpSSN; cout << "Enter gender: "; strm >> tmpGender; cout << "Enter age: "; strm >> tmpAge; p.setName(tmpName); p.setSSN(tmpSSN); p.setGender(tmpGender); p.setAge(tmpAge); return strm; }