c++中override的应用

 override是C++11中的一个继承控制保留字,放在派生类成员函数参数列表后面,用来修饰函数。派生类中被override修饰的函数,在父类中有一个与之对应(形参、函数名、返回值都一致)的虚函数,override表示要重写父类的虚函数,一旦函数后面加了override,编译器就会检查父类中是否有和子类中签名匹配的函数,如果没有编译器会报错。

示例代码:

#include "stdafx.h"
#include <iostream>
using namespace std;

class Parent 
{
public:
virtual void Func();
void Func_B();
virtual void Func_C() final{ }
};

void Parent::Func()
{
cout<<"call the function of Parent"<<endl;
}

class Child  : public Parent 
{
public:
void Func() override;//基类声明的虚函数,在派生类中也是虚函数,即使不再使用virtual关键字

/*************************************************************************
void Func_A() override;
父类中没有此方法,添加override编译会报如下错错误:
error C3668: “Child::Func_A”: 包含重写说明符“override”的方法没有重写任何基类方法
*************************************************************************/

/*************************************************************************
void Func_B() override { }
Func_B在父类中不是虚函数,添加override编译会报如下错错误:
error C3668: “Child::Func_B”: 包含重写说明符“override”的方法没有重写任何基类方法
*************************************************************************/

/*
void Func_C() override { }
Func_C在父类中被final修饰,禁止在派生类中被重写
error: Func_C在基类中声明禁止重写 
*/

};

void Child::Func()
{
cout<<"implement the function of Parent"<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
Parent objParent;
Child objChild;
return 0;
}

猜你喜欢

转载自blog.csdn.net/yu132563/article/details/80031556