如何使构造函数在两者之间返回
how to make a constructor to return in between?
我的意思是这样的
#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);
}
相关文章:
- OpenCV 函数 cv::remap() 的执行时间更长,当程序在两者之间进入睡眠状态时
- 为什么我的 cout 一次执行,尽管 cin 应该在两者之间读取?
- 为什么这个C++程序在代码::块和在线 IDE 之间返回不同的结果?
- 分段故障在类之间返回整数
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 如何区分线段和两者之间的空格?C++
- 为什么在三元运算符的分支之间返回 lambda 对某些 lambda 有效?
- 如何将数据从顶点着色器传递到介于两者之间的片段着色器
- 生成 0 或 1,而不是介于两者之间
- 为什么指针减法会导致介于两者之间的元素数量
- 告诉我两者之间的区别.它是在树上插入的C 代码
- 两者之间的最佳方法是什么:实例化对象或使用指针
- 这两者之间有什么区别?(字符)
- 这两者之间的区别。和这个>
- 两者之间的区别 |和 ||,或 & 和 &&
- 两者之间的区别
- 在c++中在多个函数之间返回和赋值向量的最佳方法
- 如何使构造函数在两者之间返回
- 动态铸造-两者之间的区别
- Linux和Windows之间返回值差异的原因是什么以及如何解决它