是否可以将"Read from file"函数分配给变量?
Is it acceptable to assign a "Read from file" function to a variable?
所以我有从文件中读取数据的FRead函数。如果函数返回错误代码,我需要完成程序。这样做可以接受吗:
string check=FRead(vec);
然后放一些 if 语句,如果检查具有某些值,则完成程序。
当我调用函数时,它是程序中唯一的实例,显然我不能多次调用它。它似乎工作正常,但我不太确定这是否是正确的方法。那么有没有一种正确的方法来做我想做的事情呢?
我还有 KRead 函数从键盘读取输入,如果出现问题,它也会返回错误代码。我这样称呼它
if(KRead=='ERROR')
return 1
可以这样做吗?
使用错误代码或异常总是更好的。两者之间的选择取决于实现。我做了一些示例应用程序,大致解释了什么是字符串错误、错误代码和异常。
字符串错误
这将起作用,但它很丑陋,而且您不知道在不消除GenerateError()
函数的情况下定义了哪些错误)。
#include <string>
#include <iostream>
class Example
{
public:
std::string GenerateError(bool error)
{
if (error)
{
return "ERROR";
}
return "OK";
};
};
int main()
{
Example example;
if ("ERROR" == example.GenerateError(true))
{
return 1; // failure
}
return 0; // success
}
错误代码
使用enum
指定可用的错误代码(在本例中为 Ok
、 Error
和 Error2
)。这使代码更易于理解,并且可以避免错误。使用枚举,您还可以使用 switch
.
#include <string>
#include <iostream>
enum ErrorCodes
{
Ok = 0,
Error,
Error2
//...
};
class Example
{
public:
ErrorCodes GenerateError(bool error)
{
if (error)
{
return ErrorCodes::Error;
}
return ErrorCodes::Ok;
};
};
int main()
{
Example example;
// Regular if statement
if (ErrorCodes::Ok == example.GenerateError(true))
{
return 1; // failure
}
else
{
return 0; // success
}
// switch statement
switch (example.GenerateError(true))
{
case Error:
case Error2:
return 1; // failure
break;
case Ok:
return 0; // success
break;
}
return 0;
}
异常
例外有点复杂,但绝对值得一试。当您想要强制函数的用户对错误执行某些操作时,请使用异常。当函数不需要对错误执行操作时,最好使用错误代码。
#include <string>
#include <iostream>
class CustomException :public std::exception{
public:
CustomException(const std::string m) :strMessage(m){}
~CustomException(void);
const char* what(){ return strMessage.c_str(); }
private:
std::string strMessage;
};
class Example
{
public:
void GenerateError(bool error)
{
if (error)
{
throw CustomException("Critical error");
}
return;
};
};
int main()
{
Example example;
try
{
example.GenerateError(true);
}
catch (CustomException ce)
{
std::cerr << ce.what() << std::endl;
return 1; // failure
}
return 0; // success
}
在C++中处理错误条件的一个好方法是让函数在出现问题时抛出异常。然后,您可以在调用它时检查异常。请参阅 http://www.cplusplus.com/doc/tutorial/exceptions/。
这
完全没问题。 就像其他人说的那样,您可以使用错误代码而不是字符串。
相关文章:
- 无法分配函数指针的 2D 数组
- Clang-Format 不能正确分配函数参数
- 我们可以在cpp中为对象分配函数吗
- 分段错误分配函数结果
- 在类内分配函数指针
- 创建一个移动分配函数,不断得到"pointer being freed was not allocated"
- 如何在C++中重新分配函数名称
- 尝试分配函数指针时获取"Void value not ignored as it ought to be"
- 尝试从文件中获取数据时,在C 中的分配函数中没有正确的字符串
- 当使用内存分配函数用作条件语句时会发生什么
- 解除分配函数的 A 函数 B 内的运行时内存
- 是否可以编写一个自定义 STL 分配器,该分配器使用指向用户提供的分配函数的指针
- 当分配函数指针时,这两种符号之间有什么区别
- 新的运算符分配函数顺序连续性和初始值
- 在类中分配函数指针会在C++中给出值类型错误
- 函数包装中的堆栈分配/函数中的alloca
- 创建线程,在循环中为其分配函数并执行
- 我想我可以理解 N5.3.4 中的 §4140/11,但已扩展的分配函数的概念对我来说是不可理解的
- 析构函数和解分配函数的区别是什么?
- 为什么分配函数使用std::nothrow_t作为引用而不是值