gpt4 book ai didi

c++ - 为什么我需要在我的子类中重新声明 `virtual` 方法? [C++/多态]

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:37 25 4
gpt4 key购买 nike

有人可以解释一下,如果我们有一个带有虚拟成员函数的抽象类,为什么我们需要在我们的代码中再次声明它子类?例如,请参见下面的示例

抽象类

.h文件

#ifndef ALGORITHM_H
#define ALGORITHM_H

#include <vector>
#include "Event.h"

using std::vector;

class Algorithm{
protected:
vector<Event>* dataset;
public:
Algorithm(vector<Event>& dataset);
virtual ~Algorithm();

virtual void run() = 0;
};

#endif

.cpp 文件

#include "../include/Algorithm.h"

Algorithm::Algorithm(vector<Event>& dataset):dataset(&dataset){}
Algorithm::~Algorithm(){}

鉴于声明了纯虚函数 run,通过扩展此类,我的预期是它需要实现。但是,它仍然需要在扩展此抽象类的类中进行声明。

小类

.h文件

#ifndef SELECT_ALGORITHM_RANDOM_H
#define SELECT_ALGORITHM_RANDOM_H

#include "Algorithm.h"

class SelectAlgorithmRandom : public Algorithm{
public:
SelectAlgorithmRandom(vector<Event>& dataset);
~SelectAlgorithmRandom();

void run(); // <-- why do I need this here, and doesn't it defy the purpose of me declaring virtual `run` function in `Algorithm`?
};

#endif

.cpp 文件

#include "../include/SelectAlgorithmRandom.h"

SelectAlgorithmRandom::SelectAlgorithmRandom(vector<Event>& dataset):Algorithm(dataset){}
SelectAlgorithmRandom::~SelectAlgorithmRandom(){}

void SelectAlgorithmRandom::run(){
// TODO
}

最佳答案

您必须添加声明,因为 C++ 标准要求类的每个成员都在类定义本身中声明:

[class.mem]/1 :

The member-specification in a class definition declares the full set of members of the class; no member can be added elsewhere.

成员 指的是函数和数据。 Algorithm 中有一个纯虚函数这一事实并不自动意味着 SelectAlgorithmRandom 也会定义它。类可以通过继承层次结构的多个层保持抽象。

要定义run 函数,您必须在类定义中明确指定该意图。

顺便说一下,在现代 C++ 中,最好将函数声明为 意味着 作为覆盖:

void run() override;

这样编译器会根据基类版本的定义检查它,以确保您确实覆盖了基类中的某些内容,而不是添加重载或一些不相关的函数。

关于c++ - 为什么我需要在我的子类中重新声明 `virtual` 方法? [C++/多态],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46952600/

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