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

pdk*_*pdk 0 c++

我的意思是这样的

#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;
    }
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 17

要处理构造函数中的错误,您应该抛出异常.
通过抛出异常,您可以通过返回来处理未完成对象创建的条件,因此无法指示对象创建是否成功或是否发生了某些错误情况.

这个 C++ FAQ是一个很好的阅读.