本地作用域、全局作用局、初始化列表、构造与析构顺序[C++ In Action][1]

1. 采用标准库的方法
2. 初始化常量数据成员的方法
3. 全局域为大括号外的所有区域
4. main()前:构建所有全局对象
5. 本地域在程序流程进入时激活
6. 离开作用域时删除对象
7. 先创建的对象后删除

标准库使用方法(一)

#include  < iostream > //采用标准库, 未使用命名空间

class  World
{
public:
    World(
int id) : _identifier(id) //构造函数前导中初始化常量成员
    
{
        std::cout
<<"Hello from "<<_identifier<<".\n"//需加前缀std::
    }

    
~World()
    
{
        std::cout
<<"Goodbye from "<<_identifier<<".\n";
    }

private:
    
const int _identifier;
}
;

World TheWorld(
1 ); //全局对象

void  main()
{
    World smallWorld(
2); //本地对象
    
for(int i=3;i<6;++i)
    
{
        World aWorld(i);
    }

    World oneMoreWorld(
6);
    
return;
}

标准库使用方法(二)

#include  < iostream > //采用标准库
using namespace std; //使用命名空间

class  World
{
public:
    World(
int id) : _identifier(id) //构造函数前导中初始化常量成员
    
{
        cout
<<"Hello from "<<_identifier<<".\n"; //不需要加前缀std::
    }

    
~World()
    
{
        cout
<<"Goodbye from "<<_identifier<<".\n";
    }

private:
    
const int _identifier;
}
;

World TheWorld(
1 ); //全局对象

void  main()
{
    World smallWorld(
2); //本地对象
    
for(int i=3;i<6;++i)
    
{
        World aWorld(i);
    }

    World oneMoreWorld(
6);
    
return;
}


标准库使用方法(三)

#include  < iostream > //采用标准库
using std::cout; //具体到命名空间中的函数
using std::endl; //具体到命名空间中的函数

class  World
{
public:
    World(
int id) : _identifier(id) //构造函数前导中初始化常量成员
    
{
        cout
<<"Hello from "<<_identifier<<endl;
    }

    
~World()
    
{
        cout
<<"Goodbye from "<<_identifier<<endl;
    }

private:
    
const int _identifier;
}
;

World TheWorld(
1 );

void  main()
{
    World smallWorld(
2);
    
for(int i=3;i<6;++i)
    
{
        World aWorld(i);
    }

    World oneMoreWorld(
6);
    
return;
}


输出结果:
Hello from 1.
Hello from 2.
Hello from 3.
Goodbye from 3.
Hello from 4.
Goodbye from 4.
Hello from 5.
Goodbye from 5.
Hello from 6.
Goodbye from 6.
Goodbye from 2.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值