c++封装多次返回
C++ wrap multiple returns
我有以下代码,它在许多行中返回ERROR:
bool func()
{
if (acondition)
{
return 0;
}
return 1;
}
int cmdfun()
{
other_funcs;
if (func()) return ERROR#NUMBER;
other_funcs;
if (func()) return ERROR#NUMBER;
}
但是我发现它变得越来越长。我怎么能封装返回error# NUMBER到func()也?或者以任何方式封装if (func())返回ERROR;变成另一个独立的函数?
仅使用return
无法真正实现这一点。
但是你可以 throw
一个异常在func
将冒泡调用堆栈,在你似乎希望程序控制的方式:
struct myexception{}; /*ToDo - inherit from std::exception?*/
bool func()
{
if (acondition){
return 0; /*normal behaviour, perhaps make `func` void if not needed?*/
}
throw myexception();
}
cmdfun
的形式为:
int cmdfun()
{
other_funcs;
func();
other_funcs;
func();
/* don't forget to return something*/
}
最后,确保您在cmdfun
的调用者中catch
异常
正如我所说的,它不是一个异常,不能通过std::exception来处理,它只是一个错误消息,error #NUMBER只是另一个宏。而且我无法访问cmdfun()的调用者。所以不能采用第一个答案。但是在询问了其他人之后,可以封装返回并节省键入它们的时间,尽管不建议这样做,但在这种特殊情况下,我可以使用宏。下面是一个完整的例子:
#include <iostream>
using namespace std;
#define CHECK_VEC(acondition)
if(checkcondition(acondition)) return -1;
bool checkcondition(bool acondition)
{
if (acondition) return 1;
return 0;
}
int fun_called_by_main()
{
int a = 5 + 4;
bool acondition = a;
CHECK_VEC(acondition);
return 1;
}
int main()
{
int a = fun_called_by_main();
cout << a << endl;
cin.get();
return 0;
}
如果我正确理解了你的问题,你是在为你自己的错误要求一个"错误报告者"。对于两种不同的情况,有两种解决方案:
情况1 -您仍然希望使用return语句来生成'错误报告器':
要做到这一点,你必须创建另一个函数,或者学习如何使用goto。然而,你不需要-你的函数返回一个布尔值(bool) -这意味着你只有两个可能的结果:0 (False)和1 (True)
bool func()
{
if (acondition)
{
return (bool)0; // False (no error)
}
return (bool)1; // True (error)
// Note: I used (bool)0 and (bool)1 because it is
// more correct because your returning type is bool.
}
void errorcase(bool trueorfalse)
{
switch(trueorfalse)
{
case False:
... // your code (func() returned 0)
break;
default:
... // your code (func() returned 1)
break;
// Note that you will not need to check if an error occurred every time.
}
return;
}
int cmdfun()
{
... // your code
errorcase(func());
... // again - your code
return 0; // I suppouse that you will return 0...
}
但我认为第二种情况更有趣(不幸的是,对于初学者来说,它也很难理解,第一种解决方案可能对你来说容易得多):
情况2 -你决定以其他方式做-那就是通过学习扔和接-我不会重复答案,因为它已经给出了:@Bathsheba回答得很好…
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- 从封装在对象中的函数 C++ 返回时为空的列表
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 如何将返回的引用封装到指向C_string的指针
- 封装与大型C 对象中的指针返回
- 我是否应该将最后一个“返回”语句封装为“else { return .. }',如果它在逻辑上是可选的
- 通过向成员返回非常量引用来破坏封装
- c++封装多次返回