如何使构造函数在两者之间返回

how to make a constructor to return in between?

本文关键字:两者之间 返回 构造函数 何使      更新时间:2023-10-16

我的意思是这样的

#include <iostream>
    using namespace std;
    class A{
            int a, b;
            public:
            A(int a,int b, int *c);
    };
    A::A(int x, int y, int *errcode)
    {
            *errcode = 0;
            a=x;
            b=y;
            // check for some error conditions
            // and return from the constructor
            if (y==0)
            {
              *errcode=-1;
              return;
            }
            // some more operations
            return;
    }
    int main() {
            int errorcode;
            A(1,0,&errorcode);
            cout << errorcode;
            return 0;
    }

要处理构造函数中的错误,应该抛出异常
通过抛出异常,您可以处理对象创建未完成的情况,只是返回,没有办法表明对象创建成功或发生了一些错误条件。

这个 c++常见问题解答对你来说是一个很好的读物。

我想你要

*errcode = 0;
不是

errcode = 0;

否则,将errcode指针设置为0

编辑:

你也可以通过使用引用而不是指针来简化你的代码:

A::A(int x, int y, int &errcode)
{
        errcode = 0;
        a=x;
        b=y;
        // check for some error conditions
        // and return from the constructor
        if (y==0)
        {
          errcode=-1;
          return;
        }
        // some more operations
        return;
}

And in your main()

A(1,0,errorcode);

允许使用return语句,就像您在这里所做的那样。(这由标准的12.1/12节规定)。但是,你不能给返回值——从构造函数返回就像从void函数返回一样。


代码中的一个小问题是errcode = 0语句。我想你说的是*errcode = 0

如果可以的话,避免在构造函数中包含可能出错的代码。但是,如果没有其他选择:

  • 使用一个成员来检查新对象是否格式良好
  • 使用工厂构建复杂对象
  • 使用初始化函数

在任何情况下,避免从构造函数/析构函数抛出异常,因为这通常是泄漏的来源。

按引用传递。

A::A(int x, int y, int& errcode){
//check error
errcode = 0;
}
int errorcode;
new A(1,2,errorcode);

在构造函数中使用return语句并没有错。另一种方法可以是在do..while循环中分组构造函数实现,如果发生错误就中断。例如

A::A(){
  do{
    //if error
    break;
  }while(0);
}