gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:36:45 25 4
gpt4 key购买 nike

我有一个 base 类:

基础.cpp:

#include "base.h"

base::base()
{
}

base::~base() {
}

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

基础.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 的类

导数.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);
}

导数.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 */

主要.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)

最佳答案

你需要在基类中创建 baseMethod virtual:

virtual void baseMethod(int);

不需要“重新确认”子类中的虚拟性,但有些人这样做是为了清楚起见。 (这也包括子类中的析构函数)。

关于c++ - 导数使用基函数而不是自己的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40549422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com