简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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