C++中初始化和定义对象的语法,带括号与不带括号的区别

本文详细探讨了C++中构造函数的使用,包括默认构造函数和带参数构造函数的调用过程。通过实例展示了不同构造函数如何初始化类成员变量,并对比了直接初始化与赋值方式的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小记:运行环境:win xp  vs2008

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::istream;
using std::ostream;

class y
{
private:
    int a;
public:
    y(){ cout << "y()" << endl;}
    y(int n){cout << "y(int n)" << endl; a = n;}
    int GetA(){return a;}
};

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;

    y *py = new y();    // 调用y(),不论 y(int n) 一般构造函数是否存在
    cout << py->GetA() << endl;        // 任意值
    y *py2 = new y;        //  调用y(),不论 y(int n) 一般构造函数是否存在
    cout << py2->GetA() << endl;    // 任意值
    y *py3 = new y(222);    // 调用 y(int n)
    cout << py3->GetA() << endl;    // 222

/*  // 结果同上,即直接初始化和采用赋值方式调用构造相同,且都不初始化成员变量

    y *py;
    py = new y();
    cout << py->GetA() << endl;    
    y *py2;
    py2 = new y;
    cout << py2->GetA() << endl;
    y *py3;
    py3 = new y(222);
    cout << py3->GetA() << endl;

*/

  system("pasue");
    return 0;
}

 

转载于:https://www.cnblogs.com/Bejadin/p/3934472.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值