多态的概念和意义
Posted 学习只为旅行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多态的概念和意义相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
//这个关键字告诉编译器print()函数
//在后面继承时有可能会被重写
virtual void print()
{
cout << "I'm Parent." << endl;
}
};
class Child : public Parent
{
public:
//子类中也可也写上virtual,也不宜不写了
void print()
{
cout << "I'm Child." << endl;
}
};
void how_to_print(Parent* p)
{
p->print(); // 展现多态的行为
}
int main()
{
Parent p;
Child c;
how_to_print(&p); // Expected to print: I'm Parent.
how_to_print(&c); // Expected to print: I'm Child.
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
virtual void func()
{
cout << "void func()" << endl;
}
virtual void func(int i)
{
cout << "void func(int i) : " << i << endl;
}
virtual void func(int i, int j)
{
cout << "void func(int i, int j) : " << "(" << i << ", " << j << ")" << endl;
}
};
class Child : public Parent
{
public:
void func(int i, int j)
{
cout << "void func(int i, int j) : " << i + j << endl;
}
void func(int i, int j, int k)
{
cout << "void func(int i, int j, int k) : " << i + j + k << endl;
}
};
void run(Parent* p)
{
p->func(1, 2); // 展现多态的特性
// 动态联编
}
int main()
{
Parent p;
p.func(); // 静态联编
p.func(1); // 静态联编
p.func(1, 2); // 静态联编
cout << endl;
Child c;
c.func(1, 2); // 静态联编
cout << endl;
run(&p);
run(&c);
return 0;
}
多态实际应用:
#include <iostream>
#include <string>
using namespace std;
class Boss
{
public:
int fight()
{
int ret = 10;
cout << "Boss::fight() : " << ret << endl;
return ret;
}
};
class Master
{
public:
virtual int eightSwordKill()
{
int ret = 8;
cout << "Master::eightSwordKill() : " << ret << endl;
return ret;
}
};
class NewMaster : public Master
{
public:
int eightSwordKill()
{
int ret = Master::eightSwordKill() * 2;
cout << "NewMaster::eightSwordKill() : " << ret << endl;
return ret;
}
};
void field_pk(Master* master, Boss* boss)
{
int k = master->eightSwordKill();
int b = boss->fight();
if( k < b )
{
cout << "Master is killed..." << endl;
}
else
{
cout << "Boss is killed..." << endl;
}
}
int main()
{
Master master;
Boss boss;
cout << "Master vs Boss" << endl;
field_pk(&master, &boss);
cout << "NewMaster vs Boss" << endl;
NewMaster newMaster;
field_pk(&newMaster, &boss);
return 0;
}
关键是父类的函数前写个virtual,不然子类传入field_pk()函数时,调用的还是父类函数,加了virtual的话就可以使用子类自己的函数了(子类不会退化为父类)
小结
以上是关于多态的概念和意义的主要内容,如果未能解决你的问题,请参考以下文章