C++中的关键字重写

函数重写 是基类函数在其派生类中的重新定义,具有相同的签名,即返回类型和参数。

null

但在某些情况下,程序员在重写该函数时可能会出错。因此,为了跟踪这种错误,C++11提出了 推翻 关键词。如果编译器遇到这个关键字,它就会理解这是同一类的重写版本。它将使编译器检查基类,以查看是否存在具有此精确签名的虚拟函数。如果没有,编译器将显示一个错误。

程序员的意图可以通过重写向编译器表明。如果override关键字与成员函数一起使用,编译器将确保该成员函数存在于基类中,并且编译器会限制程序以其他方式编译。

让我们通过下面的例子来理解:

CPP

// A CPP program without override keyword, here
// programmer makes a mistake and it is not caught
#include <iostream>
using namespace std;
class Base {
public :
// user wants to override this in
// the derived class
virtual void func() { cout << "I am in base" << endl; }
};
class derived : public Base {
public :
// did a silly mistake by putting
// an argument "int a"
void func( int a)
{
cout << "I am in derived class" << endl;
}
};
// Driver code
int main()
{
Base b;
derived d;
cout << "Compiled successfully" << endl;
return 0;
}


输出

Compiled successfully

解释 :在这里,用户打算重写派生类中的函数func(),但犯了一个愚蠢的错误,用不同的签名重新定义了函数。编译器没有检测到。然而,这个程序实际上并不是用户想要的。因此,为了避免这些愚蠢的错误,为了安全起见,可以使用override关键字。

下面是一个C++例子,说明在C++中使用重写关键字。

CPP

// A CPP program that uses override keyword so
// that any difference in function signature is
// caught during compilation
#include <iostream>
using namespace std;
class Base {
public :
// user wants to override this in
// the derived class
virtual void func() { cout << "I am in base" << endl; }
};
class derived : public Base {
public :
// did a silly mistake by putting
// an argument "int a"
void func( int a) override
{
cout << "I am in derived class" << endl;
}
};
int main()
{
Base b;
derived d;
cout << "Compiled successfully" << endl;
return 0;
}


输出(错误)

prog.cpp:17:7: error: 'void derived::func(int)'marked 'override', but does not override  void func(int a) override        ^

简而言之,它具有以下功能。这有助于检查:

  • 父类中有一个同名的方法。
  • 父类中的方法被声明为“virtual”,这意味着它将被重写。
  • 父类中的方法与子类中的方法具有相同的签名。

本文由 马扎尔·伊玛目·汗 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享