Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot declare array of strings as class member

I could not declare an array of strings in my class. Below my class definition:

class myclass{

    public:
        int ima,imb,imc;
        string luci_semaf[2]={"Rosso","Giallo","Verde"};
  };

and my main file

#include <iostream>
#include <fstream> 
#include "string.h"
#include <string>
using namespace std;
#include "mylib.h"
int main() {

    return 0;
}

Why do I get the following warnings / error?

enter image description here

like image 802
Phoenix Avatar asked Mar 10 '26 15:03

Phoenix


1 Answers

You have two problems: The first is that you can't initialize the array inline like that, you have to use a constructor initializer list. The second problem is that you attempt to initialize an array of two elements with three elements.

To initialize it do e.g.

class myclass{
public:
    int ima,imb,imc;
    std::array<std::string, 3> luci_semaf;
    // Without C++11 support needed for `std::array`, use
    // std::string luci_semaf[3];
    // If the size might change during runtime use `std::vector` instead

    myclass()
        : ima(0), imb(0), imc(0), luci_semaf{{"Rosso","Giallo","Verde"}}
    {}
};
like image 150
Some programmer dude Avatar answered Mar 12 '26 07:03

Some programmer dude