简体   繁体   English

类(具有 static 成员)在 c++ 中初始化

[英]class(with static member) initialization in c++

I was trying to understand friend functions and I found myself writing the following code我试图理解friend元函数,发现自己编写了以下代码

though I have understood the friend functions, this code leaves me with new questions:虽然我已经理解了友元函数,但这段代码给我留下了新的问题:

  1. how does the class initialise here when I havn't instantiaied any object当我没有实例化任何 object 时,class 如何在这里初始化

I know static member is shared by all objects of the class and is initialized to zero when the first object is created我知道static成员由 class 的所有对象共享,并在创建第一个 object 时初始化为零

  1. at what point does the variables base_i and derived_i get assigned to respective values from code变量base_iderived_i在什么时候被分配给代码中的相应值

I suppose it happens at return derived::derived_i + derived::base_i;我想它发生在return derived::derived_i + derived::base_i;

  1. if so, does that also allocate the memory for all the other members of class at that point, specifically also for newVar in this case如果是这样,此时是否也为 class 的所有其他成员分配 memory,在这种情况下还特别为newVar
#include <iostream>

class base
{
private:
    static int base_i;
    float newVar;
public:
    friend int addClasses();
};

int base::base_i = 5;

class derived : private base
{
private:
    static int derived_i;
public:
    friend int addClasses();
};

int derived::derived_i = 3;

int addClasses()
{
    return derived::derived_i + derived::base_i;
}

int main()
{
    std::cout<<addClasses()<<std::endl;
}

how does the class initialise here when I havn't instantiaied any object当我没有实例化任何 object 时,class 如何在这里初始化

You've initialised the variable in its definition:您已经在其定义中初始化了变量:

 int base::base_i = 5; // <-- the initialiser

The language implementation takes care of the rest.语言实现负责 rest。


at what point does the variables base_i and derived_i get assigned to respective values from code变量 base_i 和 derived_i 在什么时候被分配给代码中的相应值

Non-local variables with static storage duration are initialised before main is called.在调用main之前初始化具有 static 存储持续时间的非局部变量。


does that also allocate the memory for all the other members of class at that point, specifically also for newVar in this case这是否也为 class 的所有其他成员分配了 memory,在这种情况下也特别为 newVar

Memory for non-static member variables is "allocated" when memory for instance of the class is allocated.当 class 的实例 memory 被分配时,非静态成员变量的 Memory 被“分配”。 You didn't instantiate the class in the example program.您没有在示例程序中实例化 class。

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

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