关于C++ new 的实验

本文探讨了C++中不同类型的构造函数如何初始化类成员变量,包括默认构造函数、带参数构造函数及编译器自动生成的构造函数,并通过实例展示了它们的使用效果。

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

#include <iostream>

using namespace std;

class Anew
{
public:
    int a;
    Anew()
    {}
};

class Bnew
{
public:
    int a;
    Bnew():a(100)
    {}
};

class Cnew
{
public:
    int a;
};


int main(int argc, char *argv[])
{
    Anew tmp1;
    Anew* tmp2 = new Anew;
    Anew* tmp3 = new Anew();
    cout << tmp1.a<<endl;
    cout << tmp2->a<<endl;
    cout << tmp3->a<<endl;

    Bnew tmp11;
    Bnew* tmp22 = new Bnew;
    Bnew* tmp33 = new Bnew();
    cout << tmp11.a<<endl;
    cout << tmp22->a<<endl;
    cout << tmp33->a<<endl;

    Cnew tmp111;
    Cnew* tmp222 = new Cnew;
    Cnew* tmp333 = new Cnew();
    cout << tmp111.a<<endl;
    cout << tmp222->a<<endl;
    cout << tmp333->a<<endl;

    return 0;
}

g++ 8.1.0

输出:

0

-1163005939

-1163005939

 

100

100

100

 

2046

-1163005939

0

 

Anew  手动写了构造函数

Bnew  手动写了构造函数并有数值初始化

Cnew  编译器自带的构造函数

转载于:https://www.cnblogs.com/fundou/p/11100080.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值