例如,我有一些带有Load()函数的类。
class DB {
private:
pt_db *db;
public:
DB(const char *path);
Write(const char *path);
int Load(const char *path);
};我想根据传递的参数从Load()函数返回一些状态。
例如:
Load(<correct path to the file with valid content>) // return 0 - success
Load(<non-existent path to file>) // return 1
Load(<correct file path, but the content of the file is wrong>) // return 2不过,我也担心:
int,我可以通过错误返回其他一些状态,比如return 3 (让我们建议在Load()函数中发生了一些错误),如果我不期望这个错误代码会被传递:
int res = Load();if(res == 1) {} else (res == 2) {};. //这里我的代码由于Load()返回非预期的3值而失败。有人能帮忙吗?
发布于 2013-05-29 16:02:09
Enum是返回状态的好方法,例如:
class Fetcher{
public:
enum FetchStatus{ NO_ERROR, INVALID_FILE_PATH, INVALID_FILE_FORMAT };
private:
FetchInfo info;
public:
FetchStatus fetch(){
FetchStatus status = NO_ERROR;
//fetch data given this->info
//and update status accordingly
return status;
}
};另一种方法是使用异常。
class Fetcher{
private:
FetchInfo info;
public:
void fetch(){
if file does not exist throw invalid file path exception
else if file is badly formatted throw invalid file format exception
else everything is good
}使用枚举作为返回状态是更多的C方式,使用异常可能是更多的C++方式,但这是一个选择问题。我喜欢枚举版本,因为在我看来,它的代码更少,可读性更强。
https://stackoverflow.com/questions/16818627
复制相似问题