导数使用基函数而不是自己的函数

时间:2016-11-11 13:51:09

标签: c++ inheritance

我有一个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类派生自基础

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时,实际上我正在使用派生类的baseMethod。但是当我调用derivetiveMethod时,我使用的是基类的baseMethod。这是为什么 ?以及如何调用派生类的baseMethod? 感谢。

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

1 个答案:

答案 0 :(得分:2)

您需要在基类中生成baseMethod virtual

virtual void baseMethod(int);

需要“重新确认”儿童班的virtual,但有些人为了清晰起见而这样做。 (这也包括子类中的析构函数)。