简体   繁体   中英

how to initialize array of structures having const variables

I have an array of struct having const variables; I am initialize by using constructor initializer list, but if I make an array of that struct how to initialise all the elements of array of that structure. if the struct contains no const var, then it is easily done

if the struct contains no const var, then it is easily done

#include<iostream>
struct s_Nconst{
    int num;
    int x1;
    // s_Nconst(int);
};
int main(){
    s_Nconst sN2;
    sN2.num=5;
    std::cout<<"initial values of num\t"<<sN2.num<<std::endl;   

    //making array of s_Nconst struct
    s_Nconst sN3[sN2.num];

    for(int i=sN2.num-1; i>-1; i--,++sN2.num){
        sN3[i].x1= sN2.num;
        std::cout<<"sn3["<<i+1<<"]\t"<<sN3[i].x1<<std::endl;
    }

    return 0;
}

but if suppose the struct comprises of const var, then I am able to make single object of the struct using the constructor initializer list, but if I am going to make array of the struct it is giving error

#include<iostream>

struct s_const{
    const int x1,y1,z1;
    static int num;
    s_const(int,int,int);
};
s_const::s_const(int x,int y, int z)
        :x1(x),y1(y),z1(z) {

    std::cout<<"initial values of x1,y1,z1\t"<<this->x1<<" "<<this->y1<<" "<<this->z1<<std::endl;   
}


/*struct s_Nconst{
    int num;
    int x1;
    // s_Nconst(int);
};
 s_Nconst::s_Nconst(int x)
        :num(x){

    std::cout<<"initial values of num\t"<<this->num<<std::endl;   
} */


int main(){

    int a,b,c;
    a=1;b=2;c=3;
    s_const s1(a,b,c);

    //array of s1 is giving error
    s_const sc[3];




    //s_Nconst s2(++c);
    //s_Nconst sN2;
    //sN2.num=5;
    //std::cout<<"initial values of num\t"<<sN2.num<<std::endl;   

    //making array of s_Nconst struct
    //s_Nconst sN3[sN2.num];

    //for(int i=sN2.num-1; i>-1; i--,++sN2.num){
    //    sN3[i].x1= sN2.num;
        std::cout<<"sn3["<<i+1<<"]\t"<<sN3[i].x1<<std::endl;
    //}

    return 0;
}

is there any way to make array of structs having const variables and how to initialize them?

You can create an array of const objects, but they have to be initialized. For example, for your structs it should be:

s_const sc[3] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}};

On a side note, you might prefer std::array to built-in arrays.

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