为什么sizeof运算符不显示大小为20?

时间:2016-02-28 18:07:23

标签: c++

    #include "iostream"
    using namespace std;
    class Algebra
    {
    private:
        int a, b;
        const int c;
        const int d;
        static int s;


    public:
        //default constructor
        Algebra() : c(0), d(0)
        {
            s++;
            a = b = 0;
            cout << "Default Constructor" << endl;
        }
        //parameterized (overloaded) constructor
        Algebra(int a, int b, int c1, int d1) : c(c1), d(d1)
        {
            s++;
            setA(a);
            setB(b);
            cout << "Parameterized Constructor" << endl;
        }
        //copy (overloaded) constructor
        Algebra(const Algebra &obj) : c(obj.c), d(obj.d)
        {
            s++;
            this->a = obj.a;
            this->b = obj.b;
            cout << "Copy Constructor" << endl;
        }
        //Destructor
        ~Algebra()
        {
            s--;
            cout << "Destructor Called" << endl;
        }
        //Setter for static member s
        static void setS(int s)
        {
            Algebra::s = s;
        }

        //Getter for static member s
        static int getS()
        {
            return s;
        }

        //Getter for constant data member c
        int getC() const
        {
            return this->c;
        }

        //Setter for data member a
        void setA(int a)
        {
            if(a < 0)
                this->a = 0;
            else
                this->a = a;
        }
        //Setter for data member b
        void setB(int b)
        {
            if(b < 0)
                this->b = 0;
            else
                this->b = b;
        }
    };
    int Algebra::s = 90;
    int main()
    {
        Algebra obj1, obj2(1, 2, 3,4), obj3(obj1);
        cout << "Size of object = " << sizeof(obj1) << endl;
        return 0;
    }

为什么sizeof运算符显示大小为16,其中我已声明了int type的5个数据成员。它应该将所有5个数据成员相加并将结果赋予20.我还分别在static int变量上检查了sizeof运算符哪个工作正常。

1 个答案:

答案 0 :(得分:1)

静态成员不会影响类实例的大小,因为您只需要一个副本用于整个程序,而不是每个实例一个副本。因此,大小由4个整数组成,在您的平台上为16个字节。