简体   繁体   English

c ++中的“final”类实现

[英]“final” class implementation in c++

I was trying to understand the implementation code of "final" in cpp: 我试图理解cpp中“final”的实现代码:

following is the code: 以下是代码:

/* A program with compilation error to demonstrate that Final class cannot
   be inherited */

class Final;  // The class to be made final

class MakeFinal // used to make the Final class final
{
private:
    MakeFinal() { cout << "MakFinal constructor" << endl; }
friend class Final;
};

class Final : virtual MakeFinal
{
public:
    Final() { cout << "Final constructor" << endl; }
};

class Derived : public Final // Compiler error
{
public:
    Derived() { cout << "Derived constructor" << endl; }
};

int main(int argc, char *argv[])
{
    Derived d;
    return 0;
}

Output: Compiler Error 输出:编译器错误

In constructor 'Derived::Derived()':
error: 'MakeFinal::MakeFinal()' is private

In this I could not understand the logic of virtually inheriting the MakeFinal class. 在这里,我无法理解虚拟继承MakeFinal类的逻辑。 We could simply have inherited it(makeFinal class) as public and even in that case we would have not been able to inherit it further(because the constructor of Makefile is private and only Final class being its friend could have the access of it). 我们可以简单地将它继承(makeFinal类)作为公共,甚至在这种情况下我们将无法继续继承它(因为Makefile的构造函数是私有的,只有Final类可以访问它的朋友)。

Any pointer?? 任何指针?

It wouldn't work. 它不会起作用。 Non-virtual base classes are always initialised by the class which is immediately derived from them. 非虚基类始终由类立即初始化,该类立即从它们派生。 That is, if the scenario were as follows: 也就是说,如果方案如下:

class Final : public MakeFinal
{
public:
  Final() {}
};

class Derived : public Final
{};

then the ctor of Derived only initialises Final , which is fine ( Final has a public ctor). 然后Derived的ctor只会初始化Final ,这很好( Final有一个公共ctor)。 Final 's ctor then initialises MakeFinal , which is also possible, since Final is a friend. Final的ctor然后初始化MakeFinal ,这也是可能的,因为Final是朋友。

However, for virtual base classes, the rule is different. 但是,对于虚拟基类,规则是不同的。 All virtual base classes are initialised by the ctor of the most-derived object. 所有虚拟基类都由最派生对象的ctor初始化。 That is, when creating an instance of Final , it's Final 's ctor which initialises MakeFinal . 也就是说,在创建Final的实例时,它是Final的初始化MakeFinal的ctor。 However, when trying to create an instance of Derived , it must be Derived 's ctor which initialises MakeFinal . 但是,在尝试创建Derived实例时,它必须是Derived的ctor,它初始化MakeFinal And that is impossible, due to MakeFinal 's private ctor. 这是不可能的,因为MakeFinal的私人ctor。

Also note that C++11 introduced the keyword final for classes (and virtual functions). 另请注意,C ++ 11为类(和虚函数)引入了关键字final

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM