简体   繁体   中英

Cannot convert to struct from brace-enclosed initializer list

I looked around and couldn't find a question that answered my problem clearly so I am posting this one. I am getting this error when I try to compile my code:

welcomebits.cpp:30:74: error: could not convert ‘{tmp_fullname, tmp_user_name, tmp_PIN, tmp_balance}’ from ‘<brace-enclosed initializer list>’ to ‘User’
             User u={tmp_fullname, tmp_user_name, tmp_PIN, tmp_balance};
                                                                      ^

Why does this happen? I am new to c++ and I am just getting used to structs, classes and objects are still beyond me. I recently learned pass by reference and pointers so those I understand in the basic sense.

Here is my struct definition and the function where the error occurs:

struct User{
    std::string fullname="";
    std::string user_name="";
    float PIN=0.;
    float balance=0.;
};


void create_user_data(std::vector<User>& uv){

    std::ifstream reader;
    std::string holder="";
    char comma=',';
    std::string tmp_fullname="";
    std::string tmp_user_name="";
    float tmp_PIN=0.;
    float tmp_balance=0.;

    reader.open("database.csv");

    while(std::getline(reader, holder)){
            std::istringstream ss(holder);
            std::getline(ss, tmp_fullname, ',');
            std::getline(ss, tmp_user_name, ',');
            ss>>tmp_PIN>>comma;
            ss>>tmp_balance;

            User u={tmp_fullname, tmp_user_name, tmp_PIN, tmp_balance};
            uv.push_back(u);
    }
}

Thanks for your time and help everyone.

You need to compile with the C++14 support enabled. This is not supported in C++11 and earlier standards. C++14 allows aggregate initialization on classes / structs having member initializers. If you removed the default member initializers:

struct User{
    std::string fullname;
    std::string user_name;
    float PIN;
    float balance;
};

then your code will compile with C++11.

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