一个c++指针多态性的有关问题(上次父类没给出)
一个c++指针多态性的问题(上次父类没给出)
#include
class Display
{
public:
virtual int ShowIt(int num) {printf( "%d\n ", num); return 0;}
int ShowIt(double num) {printf( "%lf\n ", num); return 0;}
};
class DisplayEx: public Display
{
public:
int ShowIt(int num) {printf( "It is Integer, value is %d\n ", num); return 0;}
int ShowIt(const char* str) {printf( "%s\n ", str); return 0;}
};
int main()
{
DisplayEx dpex;
Display *p_base=&dpex;
p_base- > ShowIt(168);
p_base- > ShowIt(1.68)
输出什么?为什么?
------解决方案--------------------
改正一下文字:
p_base-> ShowIt(1.68);//因为Display::ShowIt(double)最匹配,而且指针的类型是Display的
//DisplayEx::ShowIt(int)和DisplayEx::ShowIt(const char*)只好靠
//边站.
//静态绑定到Display::ShowIt(double)
#include
class Display
{
public:
virtual int ShowIt(int num) {printf( "%d\n ", num); return 0;}
int ShowIt(double num) {printf( "%lf\n ", num); return 0;}
};
class DisplayEx: public Display
{
public:
int ShowIt(int num) {printf( "It is Integer, value is %d\n ", num); return 0;}
int ShowIt(const char* str) {printf( "%s\n ", str); return 0;}
};
int main()
{
DisplayEx dpex;
Display *p_base=&dpex;
p_base- > ShowIt(168);
p_base- > ShowIt(1.68)
输出什么?为什么?
------解决方案--------------------
改正一下文字:
p_base-> ShowIt(1.68);//因为Display::ShowIt(double)最匹配,而且指针的类型是Display的
//DisplayEx::ShowIt(int)和DisplayEx::ShowIt(const char*)只好靠
//边站.
//静态绑定到Display::ShowIt(double)