I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
1. C++的优点之一是使内置类型和程序员自定义类型之间无实质性区别
2. 数据成员按它们在类定义中的出现顺序进行初始化
3. 该程序首先初始化_identifier, 然后初始化_matter, 这是为什么可以在_matter构造函数中使用_identifier的值的原因
4. 初始化某个对象意味着调用它的构造函数
5. 嵌入对象按构建它们的相反顺序销毁,类似于栈的先进后出规则

World  has-a  Matter

#include <iostream>
using namespace std;

class Matter
{
public:
    Matter(
int id) : _identifier(id)
    
{
        cout
<<" Matter for "<<_identifier<<" created\n";
    }

    
~Matter()
    
{
        cout
<<" Matter in "<<_identifier<<" annihilated\n";
    }

private:
    
const _identifier;
}
;

class World
{
public:
    World(
int id) : _identifier(id), _matter(_identifier) //初始化嵌入体
    
{
        cout
<<"Hello from world "<<_identifier<<".\n";
    }

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

private:
    
const int _identifier;
    
const Matter _matter; //Matter类型的嵌入对象
}
;

World TheUniverse(
1);

void main()
{
    World smallWorld(
2);
    
return;
}

输出结果:
Matter for 1 created
Hello from world 1.
Matter for 2 created
Hello from world 2.
Goodbye from world 2
Matter in 2 annihilated

posted on 2008-01-17 11:06  jcsu  阅读(571)  评论(3编辑  收藏  举报