class(with static member) c++初始化

class(with static member) initialization in c++

我试图理解 friend 函数,发现自己编写了以下代码

虽然我理解了友元函数,但这段代码给我留下了新的问题:

  1. 当我没有实例化任何对象时,class 如何在此处初始化

I know static member is shared by all objects of the class and is initialized to zero when the first object is created

  1. 变量 base_iderived_i 在什么时候被分配给代码
  2. 中的相应值

I suppose it happens at return derived::derived_i + derived::base_i;

  1. 如果是这样,是否也为 class 的所有其他成员分配了内存,特别是在这种情况下 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

您已在其定义中初始化变量:

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

语言实现负责其余部分。


at what point does the variables base_i and derived_i get assigned to respective values from code

具有静态存储持续时间的非局部变量在调用 main 之前被初始化。


does that also allocate the memory for all the other members of class at that point, specifically also for newVar in this case

当 class 实例的内存被分配时,非静态成员变量的内存被“分配”。您没有在示例程序中实例化 class。