子类的虚函数会添加到父类虚函数表中
class A //8字节
{
char a[3];
public:
virtual void fun1(){};
};
class B : public A //12字节
{
char b[3];
public:
virtual void fun2(){};
};
子类可以定义父类中的同名成员。
子类中的成员将隐藏父类中的同名成员。
父类中的同名成员依然存在于子类中。
class A
{
public:
int _a;
};
class B : public A
{
public:
int _a;
};
int main()
{
B b;
printf("%x\n", sizeof(b)); //8
printf("%d\n", &(b._a)==&(b.A::_a)); //0
return 0;
}类的const成员初始化
class CExample
{
public:
CExample() : m_a( 1 ), m_b( 2 )
{
/*m_a = 1; compile error*/
}
~CExample()
{
}
private:
const int m_a;
//or const int m_a=1;(C++11后支持)
int m_b;
}; 总结:
对于const变量,在类内声明必须初始化。
(1)类的const成员变量必须在构造函数的参数初始化列表中进行初始化。
(2)C++11后可在类中声明时直接赋值。构造函数内部,不能对const成员赋值,编译器直接报错。
构造函数列表初始化执行顺序与成员变量在类中声明相同,与初始化列表中语句书写先后无关。

京公网安备 11010502036488号