#include<iostream>
using namespace std;
class Animal
{
private:
public:
virtual void eat(void){cout<<"eat"<<endl;}
};
class Mankind:public Animal
{
private:
public:
void eat(void){cout<<"eat rice"<<endl;}
};
class Dog:public Animal
{
private:
public:
void eat(void){cout<<"eat shit"<<endl;}
};
class Pig:public Animal
{
private:
public:
void eat(void){cout<<"root cabbage"<<endl;}
};
void func1(Animal* p){
p->eat();
}
void func2(Animal& p){不同的对象进来做不同的事,多态
p.eat();
}
int main()
{
Pig pig;
Dog dog;
Mankind man;
func2(pig);
func2(dog);
func2(man);
return 0;
}
virtual 返回类型 函数名(参数列表):通常情况下只有返回类型 函数名 参数列表都相同的函数才能构成多态,除了这一种特殊的函数
类* 函数名(参数列表)
#include <iostream>
using namespace std;
class Animal
{
private:
public:
virtual Animal *eat(void)
{
cout << "Animal eat" << endl;
return this;
}
};
class Mankind : public Animal
{
private:
public:
Mankind *eat(void)
{
cout << "man eat rice" << endl;
return this;
}
};
int main()
{
Animal a;
a.eat();
Mankind man;
Animal *p = &man;
p->eat();
return 0;
}
糟糕,内存泄漏了
#include <iostream>
using namespace std;
class Animal
{
private:
public:
Animal(){cout<<"构造Animal"<<endl;}
~Animal(){cout<<"~析构Animal"<<endl;}
void show(void){cout << "Animal eat" << endl;}
};
class Mankind : public Animal
{
private:
public:
Mankind(){cout<<"构造Mankind"<<endl;}
~Mankind(){cout<<"构造Mankind"<<endl;}
void show(void){cout << "man eat rice" << endl;}
};
int main()
{
Animal* a = new Mankind;
delete a;
return 0;
}
[root@Orz 20:55 ~]# run
构造Animal
构造Mankind
~析构Animal
[root@Orz 20:58 ~]#
虚析构函数
#include <iostream>
using namespace std;
class Animal
{
private:
public:
Animal(){cout<<"构造Animal"<<endl;}
virtual ~Animal(){cout<<"~析构Animal"<<endl;}
void show(void){cout << "Animal eat" << endl;}
};
class Mankind : public Animal
{
private:
public:
Mankind(){cout<<"构造Mankind"<<endl;}
~Mankind(){cout<<"~析构Mankind"<<endl;}
void show(void){cout << "man eat rice" << endl;}
};
int main()
{
Animal* a = new Mankind;
delete a;//删除对象animal时,重载虚析构函数,先摧毁mankind,再摧毁animal
return 0;
}
?
|