我有一个C++结构和一个方法:
struct Account
{
unsigned int id;
string username;
...
};
Account GetAccountById(unsigned int id) const { }
Run Code Online (Sandbox Code Playgroud)
如果帐户存在,我可以返回帐户结构,但如果没有帐户该怎么办?
我想过:
有没有最好的方法呢?
unw*_*ind 13
在C++中你忘记了最明显的一个:
bool GetAccountById(unsigned int id, Account& account);
Run Code Online (Sandbox Code Playgroud)
true如果帐户存在,则返回并填写提供的参考,否则返回false.
使用指针可以为null并具有以下事实也可能是方便的:
bool GetAccountById(unsigned int id, Account* account);
Run Code Online (Sandbox Code Playgroud)
true如果帐户ID存在,则可以定义为返回,但如果指针非空,则仅(当然)填写提供的帐户.有时能够测试存在是否方便,这样可以节省必须专门用于此目的的方法.
这是你喜欢的味道问题.
根据给出的选项,我会回来Account*.但返回指针可能会对接口产生一些不良副作用.
另一种可能性是在throw没有此类帐户时例外.你也可以试试boost::optional.