简体   繁体   中英

How to initialize whole array to single element in class constructor in c++

Hi I am looking to initalize whole array to single element in constructor of class.I have tried this solution but I am getting this errror.

1>C:\Users\Ahmad Mustafa Anis\source\repos\ciruclar queue\Source.cpp(8,8): error C2590: 'sig': only a constructor can have a base/member initializer list
1>Done building project "ciruclar queue.vcxproj" -- FAILED.

My code is

class CircularQueue {
public:
    int dataItems[10];
    sig() : dataItems{0, 0, 0, 0, 0, 0, 0, 0, 0, 0} { }

};

I have Visual Studio 2019, I guess c++ version in it is cpp17. If there is someway I can add a constructor and assign whole array to 0 without for loop or explicitly element by element, like this constructor


CircularQueue() {
        dataItems = { 0 };
    }

or this one

CircularQueue() {
        dataItems =  0 ;
    }

In both case my error is

error C3863: array type 'int [10]' is not assignable

If you want to initialize all values with 0

CircularQueue() : dataItems{} {}

Or,

CircularQueue() : dataItems{0,0,0,0,0,0,0,0,0,0} {}

If the array is too long, you can do this. It is not initializing . It's assigning after initialization.

CircularQueue() {
    std::fill(dataItems, dataItems+10, 3); //3 for example
}

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