你可以按照名称索引std::map
书籍。
std::map<std::string, book> books;
然后
bool modify(const std::string &name, int day, int month, int year)
{
books[name].setreleasedate(day, month, year);
return true; // always succeeds
}
这将找到name
d书books
,或自动,如果不存在,创建name
d书,然后调用book
的方法设置发布日期。
如果你不想被动态创建book
就做,你的选择是使用std::map::at
或std::map::find
std::map::at
版本:
bool modify(const std::string &name, int day, int month, int year)
{
try
{
books.at(name).setreleasedate(day, month, year);
return true;
}
catch(std::out_of_range &) // did not find named book
{
return false;
}
}
这具有在处理一个显著的性能损失如果不知名的书籍经常被抬头,那么这个例外是不寻常的。正如名称所暗示的那样,例外只应用于例外事件。更多关于为什么可以在这里阅读,如果感兴趣:Are Exceptions in C++ really slow
这也需要C++ 11标准支持来获得at
方法。
std::map::find
版本:
bool modify(const std::string &name, int day, int month, int year)
{
std::map<std::string, book>::iterator found; // could be auto found if C++11 is enabled
found = books.find(name)
if (found != books.end()) // if search ended before the end of books
{
found->setreleasedate(day, month, year);
return true;
}
else // did not find named book
{
return false;
}
}
此版本需要更多的代码,并增加了亲近微不足道的成本所有的时间,但没有失败情况下的显著处罚。
也被所有的C++支持回到标准化的开始。除非你使用Turbo C++进行开发,否则不应该有任何意外。
为什么你不能将一个对象作为参数给一个函数? 'void modify(book book,int x,int y,int z)'工作得很好。如果你想传递一个引用而不是副本,或者'void modify(book&theBook,int x,int y,int z)'。 – immibis
简短的答案在这里:写你自己的代码来做到这一点。 C++ [没有反射](https://en.wikipedia.org/wiki/Reflection_(computer_programming))。您需要实现自己的映射不透明字符串(或其他性质的标识符)的机制到离散对象中。 –
在通过搜索找到答案之前,您需要弄清楚如何正确描述您的需求!我建议把它带入聊天室进行一对一的辅导;它不适合问答数据库。 –