首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

解引用操表达式与虚函数解决办法

2012-03-13 
解引用操表达式与虚函数class base{public:virtual void fool(){cout base endl}}class deserve

解引用操表达式与虚函数
class base 
{
public:
virtual void fool(){cout << "base" << endl;}
};

class deserve : public base
{
public:
virtual void fool(){cout << "deserve" << endl;}
};

int main(int argc, char* argv[])
{
base * pb = new deserve;

  //这里调用的是base::fool()还是deserve::fool()?
(*pb).fool();
return 0;
}

vc6下测试的结果调用的是deserve::fool()。
根据c++标准,虚函数机制只针对指针和引用有效,这里*pb的静态类型是 base,既不是指针也不是引用,但是却调用的是deserve::fool()。
大家来讨论一下这个东西啊。是不是早期的vc版本很多东西不支持c++标准?有其他版本c++的同学帮忙测试一下啊。。。

[解决办法]
作为标准控,我用c++标准回答你。

在c++中,p->a()和(*p).a()是完全一样的。

For the first option (dot) the first expression shall have complete class type. For the second option (arrow) the first expression shall have pointer to complete class type. The expression E1->E2 is converted to the equivalent form (*(E1)).E2;

热点排行