17 对象的使用(二)

作用域与生存期

#include <iostream>
using namespace std;

class Test
{
public:
    Test(int n) : n_(n)
    {
        cout<<"Test "<<n_<<" ..."<<endl;
    }
    ~Test()
    {
        cout<<"~Test "<<n_<<" ..."<<endl;
    }
private:
    int n_;
};

int n;          // 未初始化的全局变量,初始值为0。n存储于.bss段中。(block started by symbol)
int n2 = 100;   // 已初始化的全局变量,初始值为100。n2存储于.data段中。
Test g(100);        // 全局对象的构造先于main函数
static Test g2(200);//静态全局对象的构造先于main函数

int main(void)
{
    cout<<"Entering main ..."<<endl;

    Test t(10);     // 栈上创建的对象,在生存期结束的时候自动释放
    {
        Test t(20);
    }

    {
        Test* t3 = new Test(30);        // 堆上创建的对象,要显示释放
        delete t3;
    }

    {
        static int n3;          // n3存储于.bss段中      (编译期初始化)
        static int n4 = 100;    // n4存储于.data段中 (编译期初始化)

        static Test t4(333);    // t4对象运行期初始化   .data段
    }
    cout<<"Exiting main ..."<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值