11.3.1重学C++之【成员变量和成员函数分开存储】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.3.1 成员变量和成员函数分开存储
        C++中,类内的成员变量和成员函数分开存储
        只有非静态成员变量才属于类的对象上
*/


class Person{

};


class Person1{
public:
    int a; // 非静态成员变量  属于类的对象上

    static int b; // 静态成员变量  不属于类的对象上
    void func(){} // 非静态成员函数  不属于类的对象上
    static void func2(){} // 静态成员函数  不属于类的对象上
};
int Person1::b = 0;


void test1(){
    Person p;
    // 空对象占用内存空间:1字节
    cout << "size of p = " << sizeof(p) << endl;
    // c++编译器给每个空对象也分配1字节空间,原因是为了区分空对象占内存的位置
    // 每个空对象也应该有一个独一无二的内存地址
}


void test2(){
    Person1 p1;
    // p1占用内存空间:4字节 <--int a;
    cout << "size of p1 = " << sizeof(p1) << endl;
}


int main(){
    test1();
    test2();

    system("pause");
    return 0;
}

posted @ 2021-03-15 18:46  yub4by  阅读(25)  评论(0)    收藏  举报