我们在前边已经知道,构造函数是C++中的一种特殊的函数,其没有返回值,在对象定义时自动被调用,主要用于对象中成员变量的初始化,但是有个问题是,我们前期一直都是默认构造函数能正常执行完毕,但是假如构造函数中执行出错,或者提前返回,会有什么情况发生?下边来看一段代码:
#include <iostream>
#include <string>
using namespace std;
class test
{
private:
int m_value1;
int m_value2;
public:
test()
{
m_value1 = 10;
return; //构造函数提前返回
m_value2 = 20;
}
int getValue1()
{
return m_value1;
}
int getValue2()
{
return m_value2;
}
};
int main()
{
test t;
cout << "t.getValue1() = " << t.getValue1() << endl;
cout << "t.getValue2() = " << t.getValue2() << endl;
system("pause");
}
编译输出: