I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
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.
posted on 2008-01-17 11:59  jcsu  阅读(556)  评论(0编辑  收藏  举报