error: could not convert ‘{0}‘ from ‘<brace-enclosed initializer list>‘ to

created at 11-12-2021 views: 16

ERROR

C++ program, using the usual initialization list today, unexpectedly reported an error

struct sales {
    char bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;
};

int main() {
    sales a = {0};
    // print(cout, a);
}

error message

cpp_primer.cc:62:17: error: could not convert '{0}' from '<brace-enclosed initializer list>' to 'sales'
   62 |     sales a = {0};
      |                 ^
      |                 |
      |                 <brace-enclosed initializer list>

solution

The problem is that the initial value is defined in the structure, and the initialization list cannot be used at this time

Change the structure to

struct sales {
    char bookNo;
    unsigned units_sold;
    double revenue;
};

That's it

summarize

Two initialization methods:

  • The initial value is given when the structure is defined
  • Initialization list assignment

The above two methods are mutually exclusive, you can only choose one to use

created at:11-12-2021
edited at: 11-12-2021: