PhonebookEntry pb1("olaNormann");
pb1.add("Home","11234567");
pb1.add("Work","11065432");
cout << pb1.getNumbers()["Home"] << endl;
cout << pb1.getNumbers()["Work"] << endl;
map<string,string>::iterator it;
for(it = pb1.getNumbers().begin(); it != pb1.getNumbers().end(); ++it){
cout << (*it).first << ": " << (*it).second << endl;
}
我已经使用了前两个 cout 来确保正确添加了两对。该代码将打印出带有 Home 和 Work 标签的前两个数字,但无法在 for 循环中打印这两个数字。for 循环只打印出“Home: 11234567”。谁能明白为什么?下面是我实现了相关方法的头文件。
class PhonebookEntry{
private:
std::string name;
std::map<std::string, std::string> numbers;
public:
PhonebookEntry(std::string name) : name(name){}
std::map<std::string, std::string> getNumbers() const {return numbers;}
void add(const std::string label,const std::string number){numbers[label] = number;}
};