首页 > 代码库 > Base类sizeof大小 -- C++
Base类sizeof大小 -- C++
Base类只是一个指针,所以Base大小是4个字节。
但Base类中添加一个int a,Base的大小变成8字节。
#include <iostream> #include <complex> using namespace std; class Base1 { public: Base1(){cout << "Base1" << endl;} ~Base1(){cout << "~Base1" << endl;} virtual void f(int){cout << "Base1 f(int)" << endl;} virtual void f(double){cout << "Base1 f(double)" << endl;} virtual void g(int i = 20){cout << "Base1 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base1 f(int)" << endl;} }; class Base2 { public: Base2(){cout << "Base2" << endl;} ~Base2(){cout << "~Base2" << endl;} virtual void f(int){cout << "Base2 f(int)" << endl;} virtual void f(double){cout << "Base2 f(double)" << endl;} virtual void g(int i = 20){cout << "Base2 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base2 f(int)" << endl;} /* 4 字节 */ int a; }; class Base3 { public: Base3(){ int a;int b;cout << "Base3" << endl;} ~Base3(){cout << "~Base3" << endl;} virtual void f(int){cout << "Base3 f(int)" << endl;} virtual void f(double){cout << "Base3 f(double)" << endl;} virtual void g(int i = 20){cout << "Base3 f(int)" << endl;} virtual void g2(int i = 10){cout << "Base3 f(int)" << endl;} /* 4 字节 */ int a; /* 4 字节 */ int b; }; int main() { Base1 a; /* 结果 4 字节 */ cout << sizeof(Base1) << endl; Base2 b; /* 结果 8 字节 */ cout << sizeof(Base2) << endl; Base3 c; /* 结果 12 字节 */ cout << sizeof(Base3) << endl; } /* [root@localhost test_class]# g++ class.cpp [root@localhost test_class]# ./a.out Base1 4 Base2 8 Base3 12 ~Base3 ~Base2 ~Base1 */
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。