乐闻世界logo
搜索文章和话题

What is the ' override ' keyword in C++ used for?

1个答案

1

The 'override' keyword in C++ is used to ensure that functions in derived classes correctly override virtual functions in the base class. Using the 'override' keyword enables the compiler to verify at compile time that the function in the derived class actually overrides a virtual function in the base class, which helps prevent errors due to spelling mistakes or mismatched function signatures.

For example, suppose we have a base class and a derived class, with a virtual function in the base class:

cpp
class Base { public: virtual void foo(int x) { std::cout << "Base foo: " << x << std::endl; } }; class Derived : public Base { public: void foo(int x) override { std::cout << "Derived foo: " << x << std::endl; } };

In this example, the derived class Derived uses the 'override' keyword to indicate that its foo function is intended to override the foo function in the base class Base. If the signature of the foo function in the Derived class is changed to void foo(double x), the compiler will report an error because there is no matching virtual function to override, which helps in promptly identifying potential errors.

2024年6月29日 12:07 回复

你的答案