简体   繁体   中英

Initialize an array inside Constructor in C++

I have defined an array within a class. I want to initialize the array with some values pre-decided value. If I could do it in definition only then it will be easier as I would have used

class A{
    int array[7]={2,3,4,1,6,5,4};
}

But, I can't do that. This, I need to do inside Constructor. But I can't use the same above syntax as it would create a new array inside Constructor and won't affect the array defined in class. What can be the easiest way to do it?

class A{
    public:
    int array[7];
    A::A(){

    }
}

You can initialize the array in the constructor member initializer list

A::A() : array{2,3,4,1,6,5,4} {

}

or for older syntax

A::A() : array({2,3,4,1,6,5,4}) {

}

Your sample should compile, using a compiler supporting the latest standard though.


Also note your class declaration is missing a trailing semicolon

class A{
    public:
    int array[7];
    A();
  };
// ^ 

With C++11 you can write this:

class C
{
    int x[4];
public:
    C() : x{0,1,2,3}
    {
        // Ctor
    }
};

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