如果在基类的虚函数声明中加上了final关键字,则表明后续的派生类不能重写该函数。

1 基类的虚函数上加上final关键字

表明基类后续的派生类不能重写该虚函数。

代码示例:

#include <iostream>
#include <memory>

using namespace std;

class Shape
{
public:
        virtual void Area() final
        {
                std::cout << "Shape Area" << std::endl;
        }
};

class Triangle : public Shape
{
public:
        // 编译错误
        virtual void Area()
        {
                std::cout << "Triangle Area" << std::endl;
        }
};


int main()
{
        std::shared_ptr<Triangle> pTriangle = std::make_shared<Triangle>();

        pTriangle->Area();

        getchar();

        return 0;
}

我们在基类Shape中普通虚函数Area中增加了final关键字,又在派生类Triangle中增加了Area的实现,此时编译器会报错。

2 派生类的虚函数加上关键字final

在派生类的虚函数加上关键final说明该派生类后续的派生类不能重写该函数!

#include <iostream>
#include <memory>

using namespace std;

class Shape
{
public:
        virtual void Area()
        {
                std::cout << "Shape Area" << std::endl;
        }
};

class Triangle : public Shape
{
public:
        virtual void Area() final;
};

class MyTriangle : public Triangle
{
public:
        // 编译错误
        virtual void Area()
        {
                std::cout << "Triangle Area" << std::endl;
        }
};


int main()
{
        std::shared_ptr<Triangle> pTriangle = std::make_shared<Triangle>();

        pTriangle->Area();

        getchar();

        return 0;
}

3 派生类的虚函数同时加上关键字override和final

在派生类类的虚函数加上关键字override和final,说明派生类后续的派生类不能重写该函数,但是当前派生类可以重写当前基类的虚函数!

#include <iostream>
#include <memory>

using namespace std;

class Shape
{
public:
        virtual void Area()
        {
                std::cout << "Shape Area" << std::endl;
        }
};

class Triangle : public Shape
{
public:
        // 正确
        virtual void Area() override final
        {
                std::cout << "Triangle Area" << std::endl;
        }
};

class MyTriangle : public Triangle
{
public:
        // 编译错误
        virtual void Area() override
        {
                std::cout << "Triangle Area" << std::endl;
        }
};


int main()
{
        std::shared_ptr<Triangle> pTriangle = std::make_shared<Triangle>();

        pTriangle->Area();

        getchar();

        return 0;
}