从抽象基类实现纯虚函数:覆盖说明符是否有任何意义? [英] Implementing pure virtual function from abstract base class: does override specifier have any meaning?
问题描述
我偶然发现了 override
的用例说明符,据我所知,似乎是多余的,并且也没有任何特殊的语义含义,但是也许我遗漏了一些东西,因此提出了这个问题.在继续之前,我应该指出,我已经尝试在SO上找到它的答案,但是我得到的最接近的是以下线程,并没有真正回答我的查询(也许有人可以指出实际上已经存在的一个问答集).回答我的问题).
I just stumbled over a use case of the override
specifier that, as far as I can tell, seems redundant and also without any particular semantics meaning, but maybe I'm missing something, hence this question. Before proceeding, I should point out that I've tried to find an answer to it here on SO, but the nearest I got were the following threads, not really answering my query (maybe someone can point out a Q&A that actually already answers my question).
考虑以下抽象类:
struct Abstract {
virtual ~Abstract() {};
virtual void foo() = 0;
};
在直接从 Abstract
派生的非抽象类中实现 foo()
时,是否有任何理由使用 override
说明符在下面的 DerivedB
中)?即,当已经需要实现 foo()
来使派生类成为非抽象类(并且不会真正覆盖任何内容)时?
Is there any reason to use the override
specifier when implementing foo()
in a non-abstract class derived directly from Abstract
(as in DerivedB
below)? I.e., when the implementation of foo()
is already required for the derived class to be non-abstract (and not really overriding anything)?
/* "common" derived class implementation, in my personal experience
(include virtual keyword for semantics) */
struct DerivedA : public Abstract {
virtual void foo() { std::cout << "A foo" << std::endl; }
};
/* is there any reason for having the override specifier here? */
struct DerivedB : public Abstract {
virtual void foo() override { std::cout << "B foo" << std::endl; }
};
推荐答案
我不是 override
的忠实拥护者,但是,假设您普遍认为这很有用,那么,是的,将 override
放在覆盖纯虚函数的虚函数上很有用.考虑下面这个人为的例子:
I'm not a big fan of override
, but, assuming it's something that you find useful in general, then, yes, putting override
on a virtual function that overrides a pure virtual functions is useful. Consider this rather contrived example:
struct Base {
virtual void f() = 0;
};
struct Derived : Base {
virtual void f();
virtual void f(int);
};
现在假设 Base
的维护者(也许甚至是您将来的自己)将 Base
更改为如下形式:
Now suppose that the maintainer of Base
(perhaps even your future self) changes Base
to look like this:
struct Base {
virtual void f(int) = 0;
};
现在, Derived
的行为已悄然改变.使用 override
时,编译器将报告错误.
Now the behavior of Derived
has quietly changed. With override
the compiler would report an error.
这篇关于从抽象基类实现纯虚函数:覆盖说明符是否有任何意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!