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

Derivative use base function instead of own function

本文关键字:自己的 函数 基函数      更新时间:2023-10-16

我有一个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。但是当我调用derivatives emethod时,我使用的是基类的baseMethod。为什么呢?我如何调用派生类的baseMethod ?谢谢。

我使用Netbeans 8.2, Windows 7 x64, g++ 5.3.0 (mingw)

您需要在基类中设置baseMethod virtual:

virtual void baseMethod(int);

不需要在子类中"重新确认"virtual性,但有些人为了清晰起见这样做。(也包括子类中的析构函数)。