一 多态的意义
如果有几个相似但不完全相同的对象,有时人们要求向它们发出同一个消息时,分别执行不同繁荣操作,这种情况就是多态现象
由继承而产生的相关的不同的类,其对象对同一消息会做出不同的反应
`父类{
void fight()`
{
cout<<"父类吃"<<eat<<endl;
}
子类{
void fight()
{
cout<<"子类吃"<<eat<<endl;
}
}
void fuzifight(父类 * chihuo)//父类 * chihuo=子类对象
{
chihuo.fight();
}
父类 *fu=new 父类(“apple”);
调用fuzifight(fu)
得到的是父类吃苹果
传进的是子类指针 得到的还是 父类吃苹果
改进:
父类中的方法改为
virtual void fight()
{
}
//这里的virtual与虚继承无关
子类如果重写这个虚函数,会得到想要的“传入谁得到谁的方法”。
**多态发生的条件:
1.要有继承
2.要有虚函数重写
3.父类指针或引用指向子类对象 **
以前的代码,可以在以后拓展,原来的接口仍然可用
// 友元函数.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<math.h>
#include<iostream>
#include<string>
using namespace std;
class Hero {
public:
virtual int getAd() {
return 10;
}
};
class AdvHero:public Hero
{
public:
virtual int getAd()//这里子类的virtual可以不写
{
return 1001;
}
private:
};
class Monster {
public:
int getAd()
{
return 1000;
}
};
void fightttt(Hero *hp, Monster *mp)
{
if (hp->getAd() > mp->getAd())//hp->getAd()发生了多态
{
cout << "英雄胜利" << endl;
}
else
cout << "怪蜀胜利" << endl;
}
int main()
{
Hero h;
Monster m;
fightttt(&h,&m);
AdvHero ah;
fightttt(&ah, &m);//hp->getAd()发生了多态
return 0;
}
多态的原理
(写了很多,可能是没保存,,只剩下这个图。。日后再补)
vptr指针
父类与子类的步长
//
#include "stdafx.h"
#include<math.h>
#include<iostream>
#include<string>
using namespace std;
class Parent {
public:
Parent(int a)
{
this->a = a;
}
virtual void print()
{
cout << "Parent :a= " << this->a << endl;
}
protected:
int a;
};
class Child :public Parent {
public:
Child(int a) :Parent(a)
{
}
virtual void print()
{
cout << "Child a= " << a << endl;
}
int b;
};
int main()
{
Child array[] = { Child(0),Child(1),Child(2) };
Parent *pp = &array[0];
pp->print();
Child *cp = &array[0];
cp->print();
/*pp++;//pp+sizeof(Parent)
cp++;//cp+sizeof(Child)
pp->print();
cp->print();*/
cout << "******************" << endl;
int i = 0;
/*for (pp = &array[0], i = 0; i < 3; i++.pp++)
{不能通过父类指针索引子类对象,因为子类有可能比父类占的空间大
pp->print();
}*/
for (cp = &array[0], i = 0; i < 3; i++,cp++)
{
cp->print();
}
return 0;
}