C++核心编程(二十)继承中的对象模型,继承中子构造和析构

复习一下:
1)静态成员函数类中声明,类外定义;
2)static 同时const修饰的成员,在定义的时候必须赋初值,否则会报错;
3)静态成员不属于类的对象上
4)静态成员函数只能访问静态成员(除非参数传递一个对象进来,通过对象访问)

(1)继承中的对象模型:
1)继承会继承父类的成员,(除了静态成员),因为它不属于类的对象上
visual studio 可以打开命令提示符:

进入存放你.cpp的文件的目录然后
输入:cl /d1 reportSingleClassLayout 类名 文件名
可以查看该文件中该类的布局

下面是一个实例:

#include<iostream>
using namespace std;

class father
{
    friend void test();//使用友元打破封装
public:
    int a;
    father();
protected:
    int b;
private:
    int c; 
    static const int d; 
};
const int father::d=10;//静态成员的定义需要在类外,static修饰的常量需要在定义的时候赋初值
void test()
{
    cout<<father::d<<endl;
}
class son:public father
{
public:
    int a;
};
int main()
{
    test();
  cout<<sizeof(son)<<endl; //son类在内存中占16个字节,继承会把除了static修饰的数据都继承,只不过不能访问的隐藏了起来,而static修饰的成员不属于类的对象上
   
}

(2)继承中子构造和析构
1)构造子类对象之前会先构造父类对象,
2) 释放父类对象之前会先释放子类对象

#include<iostream>
using namespace std;
class father
{
public:
        father();
        ~father();
};
class son:father
{
public:
        son();
        ~son();
};
father::father()
{
    cout<<"this is father_constuctor"<<endl;
}
father::~father()
{
    cout<<"this is father_distructor"<<endl;
}
son::son()
{
    cout<<"this is son_constructor"<<endl;
}
son::~son()
{
    cout<<"this is son_constructor"<<endl;
}
void test()
{
    son obj;
}
int main()
{
        test();
    /*打印结果
    this is father_constuctor
    this is son_constructor
    this is son_constructor
    this is father_distructor
    构造子类对象之前会先构造父类对象,
    释放父类对象之前会先释放子类对象
    */
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值