|
发表于 2013-7-10 22:08:03
|
显示全部楼层
- #include <iostream>
- #include <string>
- #include <map>
- using namespace std;
- class Phone {
- public:
- Phone( const string& number ):
- m_number(number),m_p_talking_to(0),m_is_talking(false){
- register_number(m_number,this);
- }
- ~Phone() {
- deregister_number(m_number);
- }
- void dial( const string& number ) {
- if( number_to_phone[number]==0 ) {
- cout<<"No this number"<<endl;
- return;
- }
- m_p_talking_to = number_to_phone[number];
- m_is_talking = true;
- m_p_talking_to->m_is_talking = true;
- m_p_talking_to->m_p_talking_to = this;
- }
- void send( const string& msg ) const {
- if( m_p_talking_to ) {
- cout<<m_number<<" is sending: "<<msg<<endl;
- m_p_talking_to->receive( msg );
- }
- }
- void endup() {
- if( m_is_talking ) {
- cout<<m_number<<" is endup"<<endl;
- m_is_talking = false;
- m_p_talking_to->endup();
- m_p_talking_to = 0;
- }
- }
- private:
- string m_number;
- Phone* m_p_talking_to;
- bool m_is_talking;
- //禁止拷贝
- Phone( const Phone& );
- Phone& operator=(const Phone& );
- void receive( const string& msg ) const {
- if( m_p_talking_to ) {
- cout<<m_number<<" receiving: "<<msg<<endl;
- }
- }
- static map<string, Phone*> number_to_phone;
- static void register_number( const string& number, Phone* p ) {
- number_to_phone[number] = p;
- }
- static void deregister_number( const string& number ) {
- number_to_phone[number] = 0;
- }
- };
- map<string, Phone*> Phone::number_to_phone;
- void test();
- int main() {
- test();
- }
- void test() {
- Phone p1("110"),p2("120");
- p1.dial("12345");
- p1.dial("120");
- p1.send(" What is your name?");
- p1.send(" Hello?");
- p1.endup();
- cout<<"==================================="<<endl;
- p1.dial("120");
- p1.send("It is me again");
- p1.send("Haaaaaaa");
- p1.endup();
- }
复制代码 |
|