我有一个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)
发布于 2016-11-11 13:55:10
您需要在基类中创建baseMethod virtual:
virtual void baseMethod(int);
你不需要在子类中“重新确认”virtual的ness,但是有些人这样做是为了清晰。(这还包括子类中的析构函数)。
https://stackoverflow.com/questions/40549422
复制相似问题