I need to write a class with an overloaded operator [], which has a different behavior when the operator [] is used to read or write data. To give a practical example of what I want to achieve, let's say I need to write an implementation of the PhoneBook class, which can be used as follows:
PhoneBook phoneBook(999999); // 999999 is the default number which should be // used when calling someone who is not in the phone book phoneBook["Paul"] = 234657; // adds Paul number phoneBook["John"] = 340156; // adds John number // next line should print Paul number 234657 cout << "To call Paul dial " << phoneBook["Paul"] << endl; // next line should print John number 340156 cout << "To call John dial " << phoneBook["John"] << endl; // next line should print 999999 because Frank is not in the phone book cout << "To call Frank dial " << phoneBook["Frank"] << endl;
The problem is that when using
phoneBook["Frank"]
I don’t want to add an entry to the phone book for Frank, otherwise a solution based on std :: map would be easy to implement.
I have not found on the Internet any standard way to achieve this. after some thought, I came up with the following solution, in which the [] operator returns a “temporary object” called PhoneNumber. PhoneNumber is then used to distinguish between read / write operations:
#include <iostream>
The PhoneBook class behaves as we would like, and the program prints:
To call Paul dial 234657 To call John dial 340156 To call Frank dial 999999
I would like to ask you some questions:
- Is there a better way to get a class behaving like class I encoded?
- Do I have a method with which I can find additional information about this?
- Do you see a flaw / possible improvement in my solution?
In the library that I am writing, allowing the behavior that I received for the PhoneBook :: [] operator in such a situation is really important, and I would really like to know what you think about my problem.
Thanks!
c ++
carlo
source share