1-问题引出.cpp
#include <iostream>
using namespace std;
class Parent
{
public:
void show()
{
cout << "this is parent" << endl;
}
};
class Child : public Parent
{
public:
void show()
{
cout << "this is Child" << endl;
}
};
int main()
{
Child c;
Parent p;
p = c;
Parent *p1 = new Child; //基类指针指向派生类对象
p1->show(); //静态联编:编译器根据p1的类型(Parent *)调用Parent里面的show函数
return 0;
}
2-多态概念.cpp
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void show() //被virtual修饰的函数叫虚函数
{
cout << "this is parent" << endl;
}
};
class Child : public Parent //1、要有继承
{
public:
void show() //2、要有虚函数重写(发生在不同的作用域中,函数原型相同)
{
cout << "this is Child" << endl;
}
};
int main()
{
Child c;
Parent p;
p = c;
Parent *p1 = new Child; //3、基类指针指向派生类对象
p1->show(); //动态联编:运行的时候才能知道p1指向什么对象
delete p1;
p1 = new Parent; //基类指针指向基类对象
p1->show(); //相同的语句有不同的执行结果(多态:多种形态)
delete p1;
return 0;
}
3-多态原理.cpp
#include <iostream>
using namespace std;
class Parent
{
public:
int a;
virtual void show()
{
cout << "thsi is parent" << endl;
}
};
class Child : public Parent
{
public:
virtual void show()
{
cout << "this is Child" << endl;
}
};
int main()
{
Parent p;
Child c;
cout << sizeof(c) << endl;
cout << sizeof(p) << endl;
cout << "Parent对象的起始地址 " << &p << endl;
cout << "成员变量a的起始地址 " << &p.a << endl;
Parent *p = new Child;
p->show(); //通过指针找到对象,通过对象前8个字节找到虚函数表,通过虚函数表找到对应的函数,调用函数(效率低)
//不要将所有函数都声明成虚函数
delete p;
p = new Parent;
p->show();
return 0;
}
4-虚析构函数.cpp
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "Parent构造函数" << endl;
}
virtual void show() //被virtual修饰的函数叫虚函数
{
cout << "this is parent" << endl;
}
virtual ~Parent()
{
cout << "Parent析构函数" << endl;
}
};
class Child : public Parent //1、要有继承
{
public:
Child()
{
cout << "Child构造函数" << endl;
}
void show() //2、要有虚函数重写(发生在不同的作用域中,函数原型相同)
{
cout << "this is Child" << endl;
}
~Child()
{
cout << "Child析构函数" << endl;
}
};
int main()
{
//Child c;
//Parent p;
//p = c;
Parent *p1 = new Child; //3、基类指针指向派生类对象
p1->show(); //动态联编:运行的时候才能知道p1指向什么对象
delete p1; //释放派生类对象 虚析构函数:通过基类指针释放派生类对象
return 0;
}