复习一下:
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
构造子类对象之前会先构造父类对象,
释放父类对象之前会先释放子类对象
*/
}