请教 不用虚函数的情况下 父类 *指针=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();