1、面向对象的三大概念、三种境界(封装,继承,多态)
封装:突破了C语言的概念,有用了类,成员函数与属性
继承: 继承可以复用以前人写的代码
多态:多态,不仅继承以前的人代码,后来人的代码
2、加了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;
}
protected:
private:
int a ;
};
class Child : public Parent
{
public:
Child(int b) : Parent(10)
{
this->b = b;
cout<<"Child b"<<b<<endl;
}
virtual void print() //virtual 父类写了virtual,子类可写可不写
{
cout<<"Child 打印 b:"<<b<<endl;
}
protected:
private:
int b;
};
void howToPrint(Parent *base) // 传来子类对象,就执行子类的函数,传来父类的对对象,就执行父类的函数
{
base->print(); //一种调用语句 有多种表现形态...
}
void howToPrint2(Parent &base)
{
base.print();
}
void main()
{
Parent *base = NULL;
Parent p1(20);
Child c1(30);
base = &p1;
base->print(); //执行父类的打印函数
base = &c1; // 根据兼容性原则,可以把子类的对象赋值给父类的指针
base->print(); //执行谁的函数 ? //面向对象新需求
{ // 使用引用的方法
Parent &base2 = p1; // 使用引用的方法
base2.print();
Parent &base3 = c1; //base3是c1 的别名
base3.print();
}
//函数调用
howToPrint(&p1);
howToPrint(&c1);
howToPrint2(p1); // 这两个是使用了引用的方法
howToPrint2(c1);
cout<<"hello..."<<endl;
system("pause");
return ;
}
运行结果:
3、如果上述我们将父类和子类中的virtual关键字去掉,就不会发生多态的情况
4、多态的需求