首先通过一个段代码来分析
#include<iostream>
class Parent//定义父类
{
public:
Parent(int a = 0)
{
this->a = a;
}
void print() //注意这里没有加virtual
{
std::cout << "我是父类" << std::endl;
//std::cout << "a:" << a << std::endl;
}
protected:
private:
int a;
};
class Child :public Parent //继承父类
{
public:
Child(int b = 0)
{
this->b = b;
}
void print()//与父类重名函数(这是重写)
{
std::cout << "我是子类" << std::endl;
//std::cout << "b:" << b << std::endl;
}
protected:
private:
int b;
};
void HowToPrint(Parent *p) //父类的指针变量
{
p->print();
}
void HowToPrint(Parent &p)//父类的引用变量
{
p.print();
}
void main()
{
Parent p1;
Child c1;
p1.print();//这里毫无疑问打印父类的print()
c1.print();//子类对象的print()
Parent *p = NULL;
p = &p1;
p->print();//调用父类的打印函数
//赋值兼容性原则遇上父类与子类同名函数的时候
p = &c1;//把子类对象赋值给父类的指针