继承
语法: class 子类 :继承方式 父类
子类 也称为派生类 父类 也称为基类
继承方式
父类中的成员在子类中会不会占有字节
在父类中所有的非静态成员属性都会被子类给继承下来
class Father
{
public:
int age;
protected:
int adress;
private:
int card;
};
class Son : public Father
{
public:
int m_a;
};
void test01()
{
Son s1;
cout << sizeof(s1) << endl;
}
int main()
{
test01();
}
// 输出结果为16
在继承中父类和子类的析构和构造函数的顺序
继承中构造的顺序是先构造父类 再构造子类 也就是先是父类的构造函数 再是子类的构造函数 而析构的顺序则正好相反
class Father
{
public:
Father()
{
cout << "father的构造函数的调用" << endl;
}
~Father()
{
cout << "father的析构函数的调用" << endl;
}
};
class Son : public Father
{
public:
Son()
{
cout << "son的构造函数的调用" << endl;
}
~Son()
{
cout << "son的析构函数的调用" << endl;
}
};
void test01()
{
Son s1;
}
/* 结果如下:
father的构造函数的调用
son的构造函数的调用
son的析构函数的调用
father的析构函数的调用*/
在继承中当父类和子类的成员同名时的处理方式
当子类中出现和父类的同名成员函数的时候 子类会隐藏掉所有的父类中的同名成员函数 如果想要去调用父类的同名成员函数 就需要加作用域
class Father
{
public:
int m_age;
Father()
{
m_age = 10;
}
void func()
{
cout << "father下的func函数的调用" << endl;
}
};
class Son : public Father
{
public:
int m_age;
Son()
{
m_age = 200;
}
void func()
{
cout << "son下的func函数的调用" << endl;
}
};
void test01()
{
Son s1;
cout << "son下的m_a: " << s1.m_age << endl;
cout << "father下的m_a: " << s1.Father::m_age << endl;
s1.func();
s1.Father::func();
}
int main()
{
test01();
}
/*
son下的m_a: 200
father下的m_a: 10
son下的func函数的调用
father下的func函数的调用
*/