Why can't I initialize the structure as follows?

struct Employee
{
    int age;
    double wage;
};

Employee joe;
joe = {2,60.0}; //using initialization list instead of doing Employee joe={2,60.0}

I get a compilation error in Visual Studio 2015, but I can execute in code blocks using the C ++ version of C ++ 11

+4
source share
2 answers

It should work.

Copy-list initialization

The following is valid and is called copy-list-initialization :

joe = {2,60.0};

This is actually temporary on the right side, which is initialized. Check out this answer .

, . , copy-list-initialization. ( ++ 11, , , ++ 11 ):

Employee joe={2,60.0}

:

joe = Employee{2,60.0};

:

Employee joe{2,60.0};

+4

struct ++ - , :

struct Employee
{
    int age;
    double wage;

    Employee(int _age, double _wage): age(_age),wage(_wage) {}
};

:

Employee joe(2, 60.0); // declaration and initialization.
+1

All Articles