我的意思是这样的
#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;
}
答案 0 :(得分:17)
要处理构造函数中的错误,您应该抛出异常 通过抛出异常,你可以通过返回来处理没有完成对象创建的条件,那么就无法指示对象创建是否成功或是否出现了一些错误情况。
This C ++常见问题解答对您来说很好。
答案 1 :(得分:4)
我想你想要
*errcode = 0;
而不是
errcode = 0;
否则,您将错误代码指针设置为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;
}
在你的主要()
A(1,0,errorcode);
答案 2 :(得分:2)
您可以使用return
语句,就像您在此处所做的那样。 (这由标准的第12.1 / 12节规定)。但是,您不能给返回值 - 从构造函数返回就像从void
函数返回一样。
代码中的一个小问题是errcode = 0
语句。我认为你的意思是*errcode = 0
。
答案 3 :(得分:0)
通过参考传递。
A::A(int x, int y, int& errcode){
//check error
errcode = 0;
}
int errorcode;
new A(1,2,errorcode);
答案 4 :(得分:0)
如果可以,请避免使用构造函数中可能出错的代码。 但是,如果你没有其他选择:
在任何情况下,都要避免从构造函数/析构函数中抛出异常,因为这通常是泄漏的来源。
答案 5 :(得分:0)
在构造函数中使用return语句没有错。另一种方法是将构造函数实现分组到do..while循环中,如果发生错误则中断。 e.g。
A::A(){
do{
//if error
break;
}while(0);
}