C++中多态是一个很重要的泛型技术,通过函数的覆盖和重写,实现接口来提高代码的复用率,提高编程效率!!
那么,在是实现多态的过程中,要注意什么问题呢?
这里需要注意:多态的实现是靠指针和引用,传值就会导致对象的分割,不能实现多态 !!
1.当一个派生类对象赋值给基类的对象时,会产生对象分割;
2.基类对象强制转化派生类对象也会,也是强制转换后赋值;
下面来看一个代码示例:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class father
{
public:
virtual void show()
{
cout<<"father!"<<endl;
}
};
class son:public father
{
public:
void show()
{
cout<<"son!"<<endl;
}
};
void show1(father f)
{
f.show();
}
void show2(father *p)
{
p->show();
}
void show3(father &f)
{
f.show();
}
int main()
{
father ff;
son ss;
father *f=new father;
son *s=new son;
ff=ss;
ff.show();//对象分割;
ff=(*s);
ff.show();//对象分割;
*f=ss;
f->show();//对象分割;
((father)ss).show();//对象分割,强转;
((father *)(&ss))->show();//指针类型的转换,成功实现多态;
f=&ss;
f->show();//传地址,成功实现多态;
father &fff=ss;
fff.show();//传引用,成功实现多态;
show1(ss); //对象分割
show2(&ss); //OK
show3(ss); //OK
system("pause");
return 0;
}
其运行的结果是;
从结果可以看出,值传递和派生类强转为基类的对象赋值并没有实现多态的效果,没有达到目的,因为在值传递的过程中,对象之间的赋值在压栈的时候只复制了father类的一部分,产生了对象分割!所以没有实现多态!