2013-10-26 198 views
1

假设有Base类和Derived类。派生类的基指针

Base *A = new Base; 

这里A是指向Base类的指针,new构造了A指向的指针。

我也看到

Base *B = new Derived; 

如何解释呢? B是一个指向Base的类,而一个Derived类构造并指向B? 如果从Base类,比如说,Virtual void f()衍生的功能,而且它在Derived类被覆盖,然后

B->f() 

会调用该函数的哪个版本?在Base类中的版本,或在Derived类中覆盖的版本。

如果Derived中有一个新功能void g(),请问B->g()会正确调用此功能吗?

一个更多的是,是

int *a = new double; 

double *a = new int; 

合法吗?

+0

谷歌'polymorphism' – texasbruce

+0

虚拟是一个关键字,它不是 '虚拟'。它使多态性的工作。 – jimifiki

回答

5

第一个问题,因为继承意味着Derived“是” Base,那么Derived是一种Base,因此是很有意义的Base *能够在它指向。

当你调用B->f(),你会得到通过Derived定义的f()版本,由Base定义不是版本(除非Derived实际上并没有重新定义它)。这(与引用一起)是在C++中获得这种多态行为的主要手段。

第二个问题,如果Derived定义一个函数g()Base一员,那么你只是将无法通过Base *调用它。当通过Base *调用函数时,只能将由接口提供的那些函数调用到Base。如果Base定义的函数g()这是virtual,那么你会得到Base版本的功能,而不是Derived版本,即使Derived重新定义它。

第三个问题:

int *a = new int; 

是合法的,但:

int *a = new double; 

因为无论int也不double是类,所以很明显double不是从int的。

+0

一个错字,3-(2)是(double * a = new int;) 但我认为根据您的解释是非法的。 – Jay

+0

是的,你假设正确。 –

3

What if there is a new function void g()in Derived, is B->g() going to invoke this function properly?

你可以这样调用它:

//! cast to derived if b really is base of derived 
derived* d= dynamic_cast<derived*>(b); 
//! d is 0 if b is not a base of derived 
if(d) 
    d-> g(); 
相关问题