当前位置:网站首页>(P13) use of final keyword

(P13) use of final keyword

2022-06-12 08:26:00 Ordinary people who like playing basketball

1.final Modify function

  • hold final Think it's a one size fits all approach
    If you use final Modify function , Only virtual functions can be modified , This prevents the subclass from overriding the function of the parent class :
class Base
{
    
public:
    virtual void test()
    {
    
        cout << "Base class...";
    }
};

class Child : public Base
{
    
public:
    void test() final
    {
    
        cout << "Child class...";
    }
};

class GrandChild : public Child
{
    
public:
    //  Grammar mistakes ,  Rewriting is not allowed 
    void test()
    {
    
        cout << "GrandChild class...";
    }
};
  • There are three classes in the above code :

Base class :Base
Subclass :Child
Grandchildren :GrandChild

  • test() Is a virtual function in the base class , Override this method in a subclass , But I don't want to continue to rewrite this method in my grandchildren , Therefore, in subclasses test() The method is marked final, There is only one use of this method in grandchildren .

2.final decorator

Use final Keyword decorated classes are not allowed to be inherited , In other words, this class cannot have derived classes .

  • Child Class is final Decorated , therefore Child Class does not allow derived classes GrandChild Class inheritance is illegal ,Child It's a kind of broken offspring .
class Base
{
    
public:
    virtual void test()
    {
    
        cout << "Base class...";
    }
};

class Child final: public Base
{
    
public:
    void test()
    {
    
        cout << "Child class...";
    }
};

// error,  Grammar mistakes 
class GrandChild : public Child
{
    
public:
};
原网站

版权声明
本文为[Ordinary people who like playing basketball]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120801094084.html