1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
// Example 9.4 SMS, Provider, Mobile
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class SMS {
private:
int from, to; // phone numbers sending
string text;
public:
SMS( int from = 0, int to = 0, string text = "" );
int getTo() const;
string toString() const;
};
class Mobile; // forward declaration
class Provider {
private:
Mobile * list;
public:
void setList( Mobile * lst ); // list = lst
Mobile *Provider :: getMobile ( int nr ); // here it goes wrong
void processMessage( const SMS & sms );
};
class Mobile {
private:
int phonenr;
Provider * provider;
SMS message;
public:
Mobile( Provider * provider = NULL, int phonenr = 0);
void receive ( const SMS & sms );
void send ( string text, int to );
string toString() const;
};
int main() {
Provider prov;
Mobile mob[10];
for( int nr = 0; nr < 10; nr++ )
mob[ nr ] = Mobile( &prov, nr);
prov.setList( mob );
mob[1].send( "I am going home now", 9 );
cout << mob[9].toString() << endl;
mob[9].send( "Ok, see you soon", 1 );
cout << mob[1].toString() << endl;
cin.get();
}
// Implementation for Mobile
Mobile :: Mobile( Provider * provider, int phonenr )
: provider(provider), phonenr(phonenr) {
}
void Mobile :: receive ( const SMS & sms ) {
message = sms;
}
void Mobile :: send( string text, int to ) {
provider -> processMessage( SMS( phonenr, to, text ) );
}
string Mobile :: toString() const {
ostringstream os;
os << "Mobile nr = " << phonenr << " " << message.toString();
return os.str();
}
// Implementation for Provider
Mobile * Provider :: getMobile( int nr ) {
return &list[nr];
}
void Provider :: setList( Mobile * lst ) {
list = lst;
}
void Provider :: processMessage( const SMS & sms ) {
int nr = sms.getTo();
Mobile * goal = getMobile( nr );
goal -> receive ( sms );
}
//Implementation for SMS
SMS :: SMS( int from, int to, string text )
: from(from), to(to), text(text) {
}
int SMS :: getTo() const {
return to;
}
string SMS :: toString() const {
ostringstream os;
os << "SMS from " << from << " to " << to << ": ";
os << text;
return os.str();
}
|