为什么虚函数需要用指针传递而不是(对象的)值传递?

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)

只有在最后一行中,您才能实现运行时多态性.

  • 谢谢,这可能是我的代码中发生的事情.维基文章的第二句话就是启示:"因为超类没有地方存储它们[孩子的属性]". (2认同)