C ++中使用的“override”关键字是什么? [英] What is the 'override' keyword in C++ used for?
本文介绍了C ++中使用的“override”关键字是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C ++的初学者。我遇到了 override
关键字在我正在工作的头文件中使用。我可以知道, override
的实际使用是什么,或许有一个例子很容易理解。
I am a beginner in C++. I have come across override
keyword used in the header file that I am working on. May I know, what is real use of override
, perhaps with an example would be easy to understand.
推荐答案
override
关键字用于两个目的:
The override
keyword serves two purposes:
- 它向代码的读者显示这是一个虚方法,即覆盖了基类的一个虚方法。
- 编译器也知道它是一个覆盖可以检查您不改变/添加您认为被覆盖的新方法。
要解释后者:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... do stuff with x and such ... }
}
class derived2: public base
{
public:
int foo(int x) override { ... }
};
在 derived2
用于改变类型。如果没有 override
,编译器最多会给出您正在使用同名隐藏虚拟方法的警告。
In derived2
the compiler will issue an error for "changing the type". Without override
, at most the compiler would give a warning for "you are hiding virtual method by same name".
这篇关于C ++中使用的“override”关键字是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文