Man*_*nux 7 c++ polymorphism inheritance virtual-functions object-slicing
我想我理解虚方法和vtable的概念,但是我不明白为什么将对象作为指针(或引用)传递并通过值传递它(将哪种方式丢弃vtable或其他东西)之间存在差异?
为什么会这样的工作:
Material* m = new Texture;
poly->setMaterial(m);
// methods from Texture are called if I keep carrying the pointer around
Run Code Online (Sandbox Code Playgroud)
而不是这个?:
Material m = Texture();
poly->setMaterial(m);
// methods from Material are called if I pass the value around
Run Code Online (Sandbox Code Playgroud)
Naw*_*waz 17
因为如果传递值,则会发生对象切片,并且无法实现运行时多态性.在您的代码中,该行Material m = Texture()导致对象切片.因此,即使您通过m指针(或引用)传递,也无法实现运行时多态性.
此外,运行时多态性通过以下方式实现:
因此,如果您想要运行时多态性,您可以使用指针或基类型的引用,这里有几个示例如何实现运行时多态:
Material* m1 = new Texture();
poly->setMaterial(m1); //achieved
Texture* t1= new Texture();
poly->setMaterial(t1); //achieved
Texture t2;
poly->setMaterial( &t2); //achieved : notice '&'
Material & m2 = t2;
poly->setMaterial( &m2 ); //achieved : notice '&'
Material m3;
poly->setMaterial( &m3 ); //NOT achieved : notice '&'
Run Code Online (Sandbox Code Playgroud)
只有在最后一行中,您才能实现运行时多态性.