微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > C++中类的内存空间大小(sizeof)分析

C++中类的内存空间大小(sizeof)分析

时间:12-01 来源:互联网 点击:

  1. cout < sizeof(derived_test) < endl;

    测试虚继承的类的大小:

    class A
    {
    char i[3];
    public:
    virtual void a(){};
    };

    class B : public virtual A
    {
    char j[3];
    public:
    virtual void b(){}
    };

    class C: public virtual B
    {
    char k[3];
    public:
    virtual void c(){}
    };

    int main()
    {
    cout < "sizeof(A): " < sizeof(A) < endl;
    cout < "sizeof(B): " < sizeof(B) < endl;
    cout < "sizeof(C): " < sizeof(C) < endl;
    return 0;
    }

    下面采用一个比较综合的例子说明一下操作系统以及各种综合的影响分析。

    #include
    #include
    #include

    class test
    {
    public:
    test();
    virtual ~test();
    virtual void get_a_c();
    private:
    int a;
    char c;
    };

    class derived_test:public test
    {
    public:
    virtual ~derived_test();
    private:
    doubled ;
    };

    class base
    {
    private:
    char a;
    static int refrence_count;
    std::string name;
    double price;
    std::vector dvec;
    public:
    base();
    virtual ~base();
    static int get_count();
    };

    int base::get_count()
    {
    return refrence_count;
    }

    int base::refrence_count = 0;

    class new_base
    {
    private:
    char a;
    double price;
    std::vector dvec;
    std::string name;
    static int refrence_count;
    public:
    new_base();
    virtual ~new_base();
    static int get_count();
    };

    int new_base::get_count()
    {
    return refrence_count;
    }
    int new_base::refrence_count = 0;

    class derived: public base
    {
    private:
    int min_qty;
    double discount;
    static int newp;
    public:
    derived();
    virtual ~derived(){};
    };

    class new_derived:public new_base
    {
    private:
    doublediscount;
    int min_pty;
    static int newp;
    public:
    new_derived();
    virtual ~new_derived(){}
    };

    int main()
    {
    std::cout < "The size of test is " < sizeof(test) < std::endl;
    std::cout < "The size of derived_test is " < sizeof(derived_test) < std::endl;
    std::cout < "The size of base is " < sizeof(base) < std::endl;
    std::cout < "The size of new_baseis " < sizeof(new_base) < std::endl;
    std::cout < "The size of derived is " < sizeof(derived) < std::endl;
    std::cout < "The size of new_derived is " < sizeof(new_derived) < std::endl;

    return 0;
    }

    上面在windows和linux的结果分别如下:
    windows:

    Linux:

    从上面的结果可以之知道在两个系统下,结果是不一样的。说明操作系统也对类的存储空间大小有较大的影响。

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top