上行
下行
重载
重定义
函数继承时,继承关系中,函数名相同即可
重写
继承关系中,返回值类型相同,函数名形同,形参列表相同,函数体不同
- #include
- using namespace std;
- class Anim{
- public:
- void test01()
- {
- cout << "动物test01" << endl;
- }
- };
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- };
- class Cat:public Anim{
- public:
- void test01()
- {
- cout << "猫类test01" << endl;
- }
- };
- void method01(Anim& a)
- {
- a.test01();
- }
- int main(int argc, char *argv[])
- {
- Dog d;
- Cat c;
- method01(d);
- method01(c);
- return 0;
- }
概念
语法
特点
补充概念
代码
- #include
- using namespace std;
- class Anim{
- public:
- virtual void test01()
- {
- cout << "动物test01" << endl;
- }
- };
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- };
- class Cat:public Anim{
- public:
- void test01()
- {
- cout << "猫类test01" << endl;
- }
- };
- void method01(Anim& a)
- {
- a.test01();
- }
- int main(int argc, char *argv[])
- {
- Dog d;
- Cat c;
- method01(d);
- method01(c);
- return 0;
- }
动态绑定条件(重要)
动态绑定原理(重要)
概念
父类的虚函数没有函数体
语法
virtual 返回值类型 函数名(形参列表) = 0;
示例
- #include
- using namespace std;
- class Anim{
- public:
- //纯虚函数
- virtual void test01() = 0;
- };
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- };
- class Cat:public Anim{
- public:
- void test01()
- {
- cout << "猫类test01" << endl;
- }
- };
- void method01(Anim& a)
- {
- a.test01();
- }
- int main(int argc, char *argv[])
- {
- Dog d;
- Cat c;
- method01(d);
- method01(c);
- return 0;
- }
注意
引入
- #include
- using namespace std;
- class Anim{
- public:
- virtual void test01() = 0;
- Anim()
- {
- cout << "父类构造" << endl;
- }
- ~Anim()
- {
- cout << "父类析构" << endl;
- }
- };
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- Dog()
- {
- cout << "子类Dog构造" << endl;
- }
- ~Dog()
- {
- cout << "子类Dog析构" << endl;
- }
- };
- int main(int argc, char *argv[])
- {
- Dog *d = new Dog();
- Anim *a = d;
- delete a;
- return 0;
- }
结果

语法
代码
- #include
- using namespace std;
- class Anim{
- public:
- virtual void test01() = 0;
- Anim()
- {
- cout << "父类构造" << endl;
- }
- virtual ~Anim()
- {
- cout << "父类析构" << endl;
- }
- };
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- Dog()
- {
- cout << "子类Dog构造" << endl;
- }
- ~Dog()
- {
- cout << "子类Dog析构" << endl;
- }
- };
- int main(int argc, char *argv[])
- {
- Dog *d = new Dog();
- Anim *a = d;
- delete a;
- return 0;
- }
结果:

语法
注意
如
- #include
- using namespace std;
- class Anim{
- public:
- virtual void test01() = 0;
- Anim()
- {
- cout << "父类构造" << endl;
- }
- virtual ~Anim() = 0;
- };
- Anim::~Anim()
- {
- cout << "父类析构" << endl;
- }
- class Dog:public Anim{
- public:
- void test01()
- {
- cout << "狗类test01" << endl;
- }
- Dog()
- {
- cout << "子类Dog构造" << endl;
- }
- ~Dog()
- {
- cout << "子类Dog析构" << endl;
- }
- };
- int main(int argc, char *argv[])
- {
- Dog *d = new Dog();
- Anim *a = d;
- delete a;
- return 0;
- }
结果
