論 「裏面的C++對象模型」 由S.利普曼,你會發現下面的摘錄26頁:爲什麼編譯器會對下面的`datum :: rotate()`使用虛擬調用?
void rotate(
X datum,
const X *pointer,
const X &reference)
{
// cannot determine until run-time
// actual instance of rotate() invoked
(*pointer).rotate();
reference.rotate();
// always invokes X::rotate()
datum.rotate();
}
main() {
Z z; // a subtype of X
rotate(z, &z, z);
return 0;
}
這一段:
The two invocations through pointer and reference are resolved dynamically. In this example, they both invoke Z::rotate(). The invocation through datum may or may not be invoked through the virtual mechanism; however, it will always invoke X::rotate().
據我所知,datum.rotate()
會始終使用靜態調用進行調用。爲什麼編譯器會在這裏使用虛擬調用?
理論上可能很有意思,但在實際代碼中按值傳遞多態類型的人應該「重新受教育」。 – Jon 2013-05-04 18:50:51