关于虚函数的一个奇怪的有关问题。

关于虚函数的一个奇怪的问题。。这是我在thinkinginc++中看到的一段代码,可是他的分析我不理解。。。555。。。base

关于虚函数的一个奇怪的问题。。
这是我在thinking   in   c++中看到的一段代码,可是他的分析我不理解。。。555。。。
base*   B[]   =   {new   base(7),   new   derived(7)       这样的话B[1]   应该是指向derived类型的吧?那为什么调用shift会有问题呢?这和shift是虚函数有什么关系吗?


class   base{
int   i;
public:
base(int   I):i(I){}
virtual   int   value()   const{return   i;}
};

class   derived:public   base{
public:
derived(int   I):   base(I)   {}
int   value()   const{
return   base::value   *   2;
}
//New   virtual   function   in   the   derived   class:
virtual   int   shift(int   x)   const{
return   base::value()   < <   x;
}
};

main(){
base*   B[]   =   {new   base(7),   new   derived(7)   };
cout < < "B[0]-> value()   =   "
< <B[0]-> value()   < <   endl;
cout < < "B[1]-> value()   =   "
< <B[1]-> value()   < <   endl;
//!   cout < < "B[1]-> shift(3)   =   "
//!         < <B[1]-> shift(3)   < <   endl;     //出错

[解决办法]
晕啊。虚函数是要靠继承的啊,在你的基类中加入以下代码
virtual int shift(int x) const{return 0;}
就好了,你再好好看看书吧,


[解决办法]
base* B[] = {new base(7), new derived(7) 这样的话B[1] 应该是指向derived类型的吧?那为什么调用shift会有问题呢?

===============
编译的时候只管这个指针被声明的类型.
而不管指针指向哪个对象. 所以就更不可能知道这个对象的动态类型了.
例如
base *pbase = 0;
p-> value();