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

请问 不用虚函数的情况下 父类 *指针=new 子类 有可能调用到子类的同名成员么

2013-08-13 
请教 不用虚函数的情况下 父类 *指针new 子类 有可能调用到子类的同名成员么?class father{public:void g

请教 不用虚函数的情况下 父类 *指针=new 子类 有可能调用到子类的同名成员么?
class father
{
public:
void get(){}
};

class son:class father
{
public:
void get(){}
};
void main()
{
father *pf=new son;
pf->get()//肯定是输出父亲的get  。如果像输出子的get  有这个可能吗?
}
[解决办法]
有,模板。WTL常见

template <class T>
class Father
{
public:
    void Do(){  cout<<"Father"<<endl;   }
    void Get(){  T* t = (T*)this; t->Do();  }
};

class Son : public Father<Son>
{
public:
    void Do(){ cout<<"Son"<<endl; }
};

Father<Son>* f = new Son;
f->Get();

热点排行