#include <iostream>
#include <cstring>
using namespace std;
class Person {
char* name;
friend class Couple;
void setName( const char * newName ) {
if( name != nullptr )
delete( name );
int nameLen = strlen( newName );
name = new char[nameLen + 1];
strcpy( name, newName );
name[nameLen] = '\0';
}
public:
friend ostream& operator<<( ostream& str, const Person& os );
explicit Person( const char* n );
Person( const Person& os );
Person& operator=( const Person& os );
~Person();
};
// implementacja zadeklarowanych funkcji
ostream& operator<<( ostream& str, const Person& os ) {
str << os.name;
return str;
}
Person::Person( const char* n ) : name( nullptr ) {
setName( n );
}
Person::Person( const Person& os ) : Person(os.name) {}
Person& Person::operator=( const Person& os ) { setName( os.name ); return *this; }
Person::~Person() {
cout << "DEL " << *this << endl;
if( name != nullptr ) delete( name );
};
class Couple {
Person *wife, *husband;
public:
friend ostream& operator<<( ostream& str, const Couple& p );
Couple( const Person& she, const Person& he );
Couple( const Couple& other );
Couple& operator=( const Couple& other );
~Couple();
};
// implementacja zadeklarowanych funkcji
ostream& operator<<( ostream& str, const Couple& c ) {
str << "Couple: he " << *(c.husband) << ", she " << *(c.wife) << endl;
return str;
}
Couple::Couple( const Person& she, const Person& he ) { wife = new Person( she ); husband = new Person( he ); }
Couple::Couple( const Couple& other ) : Couple( *( other.wife ), *( other.husband) ) {}
Couple& Couple::operator=( const Couple& other ) {
if( wife != nullptr )
delete wife;
wife = new Person( *( other.wife ) );
if( husband != nullptr )
delete husband;
husband = new Person( *( other.husband ) );
return *this;
}
Couple::~Couple() {
//cout << "DEL " << *this << endl;
if( wife != nullptr )
delete wife;
if( husband != nullptr )
delete husband;
}
int main( void ) {
Person *pjohn = new Person( "John" ),
*pjane = new Person( "Jane" );
Person mary( "Mary" ),
mark( "Mark" );
Couple *pcouple1 = new Couple( mary, *pjohn );
Couple couple2( *pjane, mark );
delete pjohn; // DEL John
delete pjane; // DEL Jane
cout << *pcouple1 << endl; // Couple : he John, she Mary
cout << couple2 << endl; // Couple : he Mark, she Jane
couple2 = *pcouple1;
/*
DEL Jane
DEL Mark
*/
delete pcouple1;
/*
DEL Mary
DEL John
*/
cout << couple2; // Couple : he John, she Mary
return 0;
/*
DEL Mary
DEL John
DEL Mark
DEL Mary
*/
}