c++封装多次返回

C++ wrap multiple returns

本文关键字:返回 封装 c++      更新时间:2023-10-16

我有以下代码,它在许多行中返回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回答得很好…