我有一个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.2
,Windows 7 x64
,g++ 5.3.0 (mingw)
答案 0 :(得分:2)
您需要在基类中生成baseMethod
virtual
:
virtual void baseMethod(int);
你不需要“重新确认”儿童班的virtual
,但有些人为了清晰起见而这样做。 (这也包括子类中的析构函数)。