2016-11-11 33 views
1

我有一個base類:衍生利用基地的功能,而不是自己的功能

base.cpp:

#include "base.h" 

base::base() 
{ 
} 

base::~base() { 
} 

void base::baseMethod(int a) 
{ 
    std::cout<<"base::baseMethod : "<<a<<std::endl; 
} 

base.h

#ifndef BASE_H 
#define BASE_H 

#include <iostream> 

class base { 
public: 
    base(); 
    base(const base& orig); 
    virtual ~base(); 
    void baseMethod(int); 

private: 
}; 

#endif /* BASE_H */ 

而且我有derivative類派生自base

derivative.cpp

#include "derivative.h" 

derivative::derivative() : base(){ 
} 

derivative::~derivative() { 
} 

void derivative::baseMethod(int a) 
{ 
    std::cout<<"derivative::baseMethod : "<<a<<std::endl; 
} 

void derivative::derivativeMethod(int a) 
{ 
    baseMethod(a); 
    derivative::baseMethod(a); 
} 

derivative.h

#ifndef DERIVATIVE_H 
#define DERIVATIVE_H 

#include "base.h" 

class derivative : public base{ 
public: 
    derivative(); 
    derivative(const derivative& orig); 
    virtual ~derivative(); 

    void derivativeMethod(int); 
    void baseMethod(int); 
private: 

}; 

#endif /* DERIVATIVE_H */ 

的main.cpp

derivative t; 
t.baseMethod(1); 
t.derivativeMethod(2); 

和輸出是:

derivative::baseMethod : 1 
base::baseMethod : 2 
base::baseMethod : 2 

當我打電話baseMethod用衍生物的類對象,實際上我使用派生類的基本方法。但是當我調用derivetiveMethod時,我正在使用基類的baseMethod。這是爲什麼 ?以及如何調用派生類的baseMethod? 謝謝。

我使用Netbeans 8.2Windows 7 x64g++ 5.3.0 (mingw)

+1

您沒有將'baseMethod'標記爲'virtual'。 –

+1

不是問題,但只是讓你知道它被稱爲派生,而不是派生。當你派生一個類時,它就變成了派生類。 – NathanOliver

+4

[我無法複製它](http://ideone.com/XlJbBs)。 –

回答

2

你需要讓baseMethodvirtual在基類:

virtual void baseMethod(int);

需要 「重新確立的」 virtual在孩子班,但有些民衆爲了清晰起見。 (這也包括子類中的析構函數)。

+1

您也可以「重申」派生類的函數使用override來覆蓋基類虛函數的事實。這比爲了清晰起見而做得更強一些。 – SirGuy