内联虚拟功能真的没有意义吗?当我收到代码评论评论说虚拟功能不需要内联时,我收到了这个问题。我认为在直接在对象上调用函数的场景中,内联虚函数可以派上用场。但是我想到的反驳论点是 - 为什么要想定义虚拟然后使用对象来调用方法呢?最好不要使用内联虚拟功能,因为它们几乎从未扩展过吗?我用于分析的代码片段: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;}
- 3 回答
- 0 关注
- 424 浏览
添加回答
举报
0/150
提交
取消