1.概念
类有三个重要的性质-封装、 继承、多态。其中多态有点难理解
通俗的说接口的多种不同实现方式即为多态(允许你将父对象设置成为一个或者更多的他的子对象相等的技术),赋值之后父对象就可以根据当前子对象给他的赋值,以子对象的特性(以子对象的方式)运行。
class food
{
public:
void price()
{
cout<<"the food price"<<endl;
}
void weight()
{
cout<<"the food weight"<<endl;
}
private:
int chengben;
};
class vegetables: public food
{
void price()
{
cout<<"the vegetables price"<<endl;
}
private:
int chengben;
};
int main()
{
vegetables shucai;
food *shiwu=&shucai;
shiwu->price();
return 0;
}
上面输出的结果是
the food price
为什么把子类的地址给父类的指针后执行的仍然不是子类的属性和方法呢?
这里就要讲多态的问题
上面的例子根本没实现类的多态,要想实现有什么方法呢?引入虚函数
class food
{
public:
virtual void price()
{
cout<<"the food price"<<endl;
}
void weight()
{
cout<<"the food weight"<<endl;
}
private:
int chengben;
};
class vegetables: public food
{
void price()
{
cout<<"the vegetables price"<<endl;
}
private:
int chengben;
};
int main()
{
vegetables shucai;
food *shiwu=&shucai;
shiwu->price();
return 0;
}
输出的结果是
the vegetables price
这样就实现了类的多态---父类的对象通过不同的赋值,达到实现子类的不同的状态。
C++的多态性:在基类的函数前加vitual关键字,在派生类中重写该函数(不用加vitual),运行时将会根据对象的实际类型来调用相应的函数。如果对象类型是子类,就调用子类的函数,如果对象类型是父类,就调用父类的函数。