#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int a){
this->a = a;
cout<<"Parent a:"<<a<<endl;
}
void print(){
cout<<"Parent 打印a:"<<a<<endl;
}
private:
int a;
};
class Child :public Parent
{
public:
Child(int b):Parent(10){
this->b = b;
cout<<"Child b:"<<b<<endl;
}
void print(){
cout<<"Child 打印b:"<<b<<endl;
}
private:
int b;
};
void howToPrint(Parent *base)
{
base->print();
}
void howToPrint2(Parent &base)
{
base.print();
}
int main(){
Parent *base = NULL;
Parent p1(20);
Child c1(40);
base =&p1;
base->print();
base = &c1;
base->print();
{
Parent &base2 = p1;
base2.print();
Parent &base3 = c1;
base3.print();
}
howToPrint(&p1);
howToPrint(&c1);
howToPrint2(p1);
howToPrint2(c1);
system("pause");
}
父类中被重写的函数依然会继承给子类,默认情况下子类中重写的函数将隐藏父类中的函数,通过作用域分辨符::可以访问到父类中被隐藏的函数。
这种现象产生的原因:
C/C++是静态编译型语言,在编译时,编译器自动根据指针的类型判断指向的是一个什么样的对象。静态链编
1、在编译此函数的时,编译器不可能知道指针 p 究竟指向了什么。
2、编译器没有理由报错。
3、于是,编译器认为最安全的做法是编译到父类的print函数,因为父类和子类肯定都有相同的print函数。
但是,在实际的过程应用中产生了这么一个新需求:根据实际的对象类型来判断重写函数的调用
//面向对象新需求
//如果我传一个父类对象,执行父类的print函数
//如果我传一个子类对象,执行子类的printf函数
解决方案
Ø C++中通过virtual关键字对多态进行支持
Ø 使用virtual声明的函数被重写后即可展现多态特性
#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int a){
this->a = a;
cout<<"Parent a:"<<a<<endl;
}
virtual void print(){
cout<<"Parent 打印a:"<<a<<endl;
}
private:
int a;
};
class Child :public Parent
{
public:
Child(int b):Parent(10){
this->b = b;
cout<<"Child b:"<<b<<endl;
}
void print(){
cout<<"Child 打印b:"<<b<<endl;
}
private:
int b;
};
void howToPrint(Parent *base)
{
base->print();
}
void howToPrint2(Parent &base)
{
base.print();
}
int main(){
Parent *base = NULL;
Parent p1(20);
Child c1(40);
base =&p1;
base->print();
base = &c1;
base->print();
{
Parent &base2 = p1;
base2.print();
Parent &base3 = c1;
base3.print();
}
howToPrint(&p1);
howToPrint(&c1);
howToPrint2(p1);
howToPrint2(c1);
system("pause");
}