我想我理解虚拟方法和 vtables 的概念,但我不明白为什么将对象作为指针(或引用)传递和按值传递(哪种废弃 vtable 或什么?)
为什么这样的东西会起作用:
Material* m = new Texture;
poly->setMaterial(m);
// methods from Texture are called if I keep carrying the pointer around
而不是这个?
Material m = Texture();
poly->setMaterial(m);
// methods from Material are called if I pass the value around
最佳答案
因为如果你按值传递,那么 object slicing会发生,无法实现运行时多态性。在您的代码中,正是 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 '&'
只有最后一行没有实现运行时多态性。
关于c++ - 为什么虚函数需要通过指针而不是(对象的)值传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5821075/