#include<iostream>
using namespace std;
class Parent
{
public:
Parent(int a)
{
this->a = a;
cout << " Parent" << a << endl;
}
public:
virtual void print()//在子类里面可写可不写
{
cout << "Parent" <<a<< endl;
}
protected:
private:
int a;
};
class Child:public Parent
{
public:
Child(int b):Parent(10)
{
this->b = b;
cout << " Child b" << b << endl;
}
public:
void print()
{
cout << "Child" <<b<< endl;
}
protected:
private:
int b;
};
void main()
{
//可以把子类的对象赋值给指针
Parent* base = NULL;
Parent p1(20);
Child c1(30);
base = &p1;
base->print();//父类
base = &c1;
base->print();//执行谁的 ->面向对象新需求
return;
}
多态如何演变:
#include<iostream>
using namespace std;
class HeroFighter
{
public:
virtual int power()
{
return 10;
}
};
class EncmyFighter
{
public:
int attact()
{
return 15;
}
};
class AdvHeroFighter :public HeroFighter
{
public:
virtual int power()
{
return 10;
}
};
//
class AdvAdvHeroFighter :public HeroFighter
{
public:
virtual int power()
{
return 30;
}
};
void play(HeroFighter *hf, EncmyFighter *ef)
{
//多态场景
if (hf->power() > ef->attact())//hf->power() 会有多态发生
{
cout << "hero win" << endl;
}
else
{
cout << "hero faule" << endl;
}
}
void main()
{
HeroFighter hf;
EncmyFighter ef;
AdvHeroFighter advhf;
//
AdvAdvHeroFighter advadvhf;
play(&hf, &ef);
play(&advhf, &ef);
//
play(&advadvhf, &ef);//这个框架能把后来写的代码调用起来
}
//多态框架
//play 给对象搭建舞台 看成一个框架
//封装:突破函数 用类做函数参数时候 可以使用对象的属性和对象的方法
//继承: A B代码复用
//多态:可以使用未来
//实现多态的三个条件:1.要有继承 2.要有函数重写3.父类指针指向子类对象
//void main01()
//{
// HeroFighter hf;
// EncmyFighter ef;
// AdvHeroFighter advhf;
// if (hf.power() > ef.attact())
// {
// cout << "hero win" << endl;
// }
// else
// {
// cout << "hero faule" << endl;
// }
// if (advhf.power() > ef.attact())
// {
// cout << "hero win" << endl;
// }
// else
// {
// cout << "hero faule" << endl;
// }
// return;
//}
虚析构
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class A
{
public:
A()
{
p = new char[20];
strcpy(p, "obja");
cout << "a" << endl;
}
virtual ~A()
{
delete[] p;
cout << "~a" << endl;
}
protected:
private:
char* p;
};
class B :public A
{
public:
B()
{
p = new char[20];
strcpy(p, "obja");
cout << "b" << endl;
}
~B()
{
delete[] p;
cout << "~b" << endl;
}
protected:
private:
char* p;
};
class C :public B
{
public:
C()
{
p = new char[20];
strcpy(p, "obja");
cout << "c" << endl;
}
~C()
{
delete[] p;
cout << " ~`c" << endl;
}
protected:
private:
char* p;
};
//只执行了父类的析构
//通过父类指针把子类的析构函数都执行一遍
//释放所有的子类资源 只能用virtual
void howtodelete(A *base)
{
delete base;//不会表现成多态
}
void main()
{
C* myc = new C;//how delete 匹配 new会自动调用~函数
howtodelete(myc);
return;
}
!在这里插入图片描述