C++中构造函数之二阶构造模式

    我们在前边已经知道,构造函数是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");
}

编译输出:

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值