当我收到一条代码审查评论说虚函数不需要内联时,我得到了这个问题。
我认为内联虚函数可以在直接在对象上调用函数的场景中派上用场。但我想到的相反论点是——为什么要定义虚拟然后使用对象来调用方法?
最好不要使用内联虚函数,因为它们几乎从未扩展过?
我用于分析的代码片段:
class Temp
{
public:
virtual ~Temp()
{
}
virtual void myVirtualFunction() const
{
cout<<"Temp::myVirtualFunction"<<endl;
}
};
class TempDerived : public Temp
{
public:
void myVirtualFunction() const
{
cout<<"TempDerived::myVirtualFunction"<<endl;
}
};
int main(void)
{
TempDerived aDerivedObj;
//Compiler thinks it's safe to expand the virtual functions
aDerivedObj.myVirtualFunction();
//type of object Temp points to is always known;
//does compiler still expand virtual functions?
//I doubt compiler would be this much intelligent!
Temp* pTemp = &aDerivedObj;
pTemp->myVirtualFunction();
return 0;
}