简体   繁体   English

在 C++ 中的类声明中声明的函数如何执行?

[英]How functions executed declared inside class declaration in c++?

Some code contains function invoked inside class declaration.一些代码包含在类声明中调用的函数。

class Example
{
   public:
    bool keyBlobClosed = deviceClosed()?true:false;
};

In this case, deviceClosed() function gets executed when object created or when class declaration created in memory?在这种情况下,deviceClosed() 函数在创建对象时或在内存中创建类声明时执行?

This is called a default member initializer .这称为默认成员初始值设定项 It is allowed on non-static members (as you have used here) since C++11.自 C++11 以来,它被允许用于非静态成员(如您在此处使用的那样)。

It is equivalent to providing a member initializer list that performs the same initialization:相当于提供了一个成员初始化列表,执行相同的初始化:

class Example {
public:
    bool keyBlobClosed;
    Example() 
        : keyBlobClosed(deviceClosed())
    {
    }
};

Obviously, this will cause deviceClosed() to be called whenever Example is instantiated.显然,这将导致在实例化实例时调用 deviceClosed()。 The return value of deviceClosed() will be used to initialize keyBlobClosed. deviceClosed() 的返回值将用于初始化 keyBlobClos​​ed。

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

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