简体   繁体   English

C ++:访问struct元素的初始化构造函数

[英]C++: access initialization constructor for struct elements

Suppose I have a struct with a type that possesses a constructor: 假设我有一个结构体具有构造函数的结构:

struct my_struct {
   array2D<double> arr;
   array2D<double> arr2; etc.
}

// where I would typically generate arr like: 
int n = 50; int m = 100;
array2D<double> arr(n,m);

Right now, I initialize my struct as follows: 现在,我将结构初始化如下:

struct my_struct {
    array2D<double> arr;
    my_struct(n,m){
        array2D<double> this_arr(n,m);
        this->arr = this_arr;
    }
}

Is there a way to access the constructor like so (in pseudo code): 有没有办法像这样(用伪代码)访问构造函数:

struct my_struct{
    array2D<double> arr;
    my_struct(n,m){
         this->arr(n,m);
    }
}

Right now, I am holding pointers in my struct...but then using the struct is beside the point, because I am trying to use the struct to clean up the code. 现在,我将指针保存在我的结构中...但是使用结构是不重要的,因为我试图使用该结构来清理代码。

Use a member initializer list: 使用成员初始化器列表:

struct my_struct{
    array2D<double> arr;
    my_struct(n,m)
         : arr(n,m)
    {
    }
}

What you're looking for is the initializer list: 您正在寻找的是初始化列表:

struct my_struct{
    array2D<double> arr;
    my_struct(n,m) : arr(n, m) { }
}

You need to make use of the constructor's initializer list . 您需要利用构造函数的初始化程序列表 Before the constructor's body, you may list any of that class' members or base class for initialization. 在构造函数的主体之前,您可以列出该类的任何成员或基类以进行初始化。

struct my_struct 
{
    array2D<double> arr;
    my_struct(int n, int m) : arr(n, m)
    { }
};

Members and base classes that do not appear in the initializer list (or all of them if the list is not present) will first be default constructed. 不会在初始化列表中出现的成员和基类(如果列表不存在,则不出现在所有成员和基类中)将首先被默认构造。 Even if you try to assign a value to those members in the body of the constructor, they will still first be initialized with no arguments. 即使您尝试为构造函数主体中的那些成员分配值,它们也仍将首先不带任何参数进行初始化。 Note that base classes are initialized first, then the members in the order they appear in the class declaration regardless of the order they appear in the initializer list. 请注意,首先初始化基类,然后按照成员在类声明中出现的顺序对其进行初始化,而不考虑它们在初始化列表中出现的顺序。

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

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