new对象时,类名后加括号与不加括号的区别

http://www.cnblogs.com/Braveliu/p/4263145.html

#include <iostream>
using namespace std;

// 空类
class empty
{
};

// 一个默认构造函数,一个自定义构造函数
class Base
{
public:
    Base() 
    { 
        cout << " default Base construct " << endl;
        m_nValue = 100; 
    };
    Base(int nValue) 
    { 
        cout << " custom Base construct " << endl;
        m_nValue = nValue; 
    };

private:
    int m_nValue;
};

// 一个默认复合构造函数
class custom
{
public:
    custom(int value = 100)
    { 
        cout << " default && custom construct " << endl;
        m_nValue = value; 
    }

private:
    int m_nValue;
};

void main()
{
    empty* pEmpty1 = new empty;
    empty* pEmpty2 = new empty();

    Base* pBase1 =  new Base;
    Base* pBase2 = new Base();
    Base* pBase3 = new Base(200);

    custom* pCustom1 = new custom;
    custom* pCustom2 = new custom();

    delete pEmpty1;
    delete pEmpty2;

    delete pBase1;
    delete pBase2;
    delete pBase3;

    delete pCustom1;
    delete pCustom2;
}
// Result:
/*
<span style="background-color: rgb(255, 153, 102);">default Base construct
default Base construct
custom Base construct
default && custom construct
default && custom construct</span>
*/


总结:   1.如果类中有自己定义的构造函数,不论有无参数,编译器就不会为其生成默认的构造函数。

            所以,这种情况,有无括号都相同;

            2.有无括号主要在以下情况下才会有区别:

               类中有两个或两个以上的构造函数,一个为无参构造函数,其他构造函数 : 有一个或者多个参数(这些参数都必须在参数中指定默认值) 的情况;

               在这种情况下,如果调用有括号的,则表示调用无参构造函数,如果不写括号,则编译器不知道你到底是要调用哪个构造函数,从而报错;

      






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值