#include<iostream.h>class Base
{
public:
virtual Base* afn()
{
cout<<"This is Base class.\n";
return this;
}
};
//class SubClass:public Base
{
public:
SubClass * afn()
{
cout<<"This is SubClass.\n";
return this;
}
};
//void test(Base& x)
{
Base* b;
b=x.afn();
}
//void main()
{
Base bc;
SubClass sc;
test(bc);
test(sc);
}
编译显示:error C2555: 'SubClass::afn' : overriding virtual function differs from 'Base::afn' only by return type or calling convention
把virtual都加上或都去掉,编译正确但得到的结果有问题。
{
public:
virtual Base* afn()
{
cout<<"This is Base class.\n";
return this;
}
};
//class SubClass:public Base
{
public:
SubClass * afn()
{
cout<<"This is SubClass.\n";
return this;
}
};
//void test(Base& x)
{
Base* b;
b=x.afn();
}
//void main()
{
Base bc;
SubClass sc;
test(bc);
test(sc);
}
编译显示:error C2555: 'SubClass::afn' : overriding virtual function differs from 'Base::afn' only by return type or calling convention
把virtual都加上或都去掉,编译正确但得到的结果有问题。
{
public:
virtual void afn()
{
cout<<"This is Base class.\n";
}
};
//class SubClass:public Base
{
public:
void afn()
{
cout<<"This is SubClass.\n";
}
};
///*void test(Base& x)
{
Base* b;
b=x.afn();
};
//
*/
void main()
{
Base *p;
Base bc;
SubClass sc;
p=&bc;
p->afn();
p=≻
p->afn();//多态(迟后联编)是指基类的指针或引用可以根据指向对象的不同调用不同的函数。
}
To:danlansky(忧郁蓝色) 你说的对,这属于多态中的虚拟函数