码迷,mamicode.com
首页 > 编程语言 > 详细

C++对象模型学习笔记

时间:2014-12-02 20:44:41      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   strong   on   div   

1. 全局变量是如何初始化的

//global var
A a;

int main()
{
    cout<<a<<endl;
    return 0;  
} 

  如上述例子,全局变量a是在main()函数之前便被初始化的,但是它是如何被初始化的呢?答案是所谓的静态初始化

2. C++对C进行封装的布局成本

  C++在布局和存取时间上主要的额外负担是由virtual 机制引起的,包括:

      virtual function机制:用于支持有效率的“执行期绑定”

      virtual base class:用以实现“多次出现在继承体系中的base class ,有一个单一而被共享的实体”

  此外,还有一些多重继承下的额外负担,发生在“一个derived class 和其第二或后继之 base class 的转换”之间。然而,一般而言,并没有什么天生的理由说C++程序一定比C兄弟庞大或迟缓。

3. 父类与子类的指针有什么不同?

  看下面例子:

class ZooAnimal
{
public:
    ZooAnimal(): name("")
    {
        cout<<"ZooAnimal::ZooAnimal()"<<endl;
    }

    ZooAnimal(string str): name(str)
    {
        cout<<"ZooAnimal::ZooAnimal(string)"<<endl;
    }

    virtual ~ZooAnimal()
    {
        cout<<"ZooAnimal::~ZooAnimal()"<<endl;
    }

    virtual void rotate()
    {
        cout<<"ZooAnimal::rotate()"<<endl;
    }


protected:
    int loc;
    string name;
};



class Bear: public ZooAnimal
{
public:
    Bear()
    {
        cout<<"Bear::Bear()"<<endl;
    }

    Bear(string str): ZooAnimal(str)
    {
        cout<<"Bear::Bear(string)"<<endl;
    }

    ~Bear()
    {
        cout<<"Bear::~Bear()"<<endl;
    }

    void rotate()
    {
        cout<<"Bear::rotate()"<<endl;
    }

    virtual void dance()
    {
        cout<<"Bear::dance()"<<endl;
    }


protected:
    enum Dances{DAN, SLEEP};

    Dances dances_known;
    int cell_block;
};


int main()
{
    cout<<"sizeof(ZooAnimal):"<<sizeof(ZooAnimal)<<endl;
    cout<<"sizeof(Bear):"<<sizeof(Bear)<<endl;

    Bear b("Yogi");
    Bear *pb = &b;
    ZooAnimal *pbr = &b;
    
    return 0;
}

  指针pb 和 pbr 有什么不同呢?它们都指向Bear对象b的第一个字节,其间的差别是,pb所涵盖的地址包含了整个Bear 对象,而 pbr 所涵盖的地址只包含Bear 对象中的ZooAnimal 部分!

 

C++对象模型学习笔记

标签:style   blog   io   ar   color   sp   strong   on   div   

原文地址:http://www.cnblogs.com/wiessharling/p/4138308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!