Defining structure variable after structure type

后端 未结 3 647
眼角桃花
眼角桃花 2020-12-22 03:53
#include 

struct people 
{
    int id;
} person; // that part

int main()
{
    person = {3};   
    std::cout << person.id;

    return 0;
}
         


        
相关标签:
3条回答
  • 2020-12-22 04:28

    You can't use the structure initialization syntax in a normal assignment, it has to be done when you declare your variable:

    struct people 
    {
        int id;
    } person = { 3 };
    

    If you have a C++11 compatible compiler, you can use the uniform initialization syntax to copy later though:

    person = people { 3 };
    
    0 讨论(0)
  • 2020-12-22 04:42

    Once I've seen some keyword after structure, like the "person" here.

    It's not a keyword, it's a name. You're allowed to declare variables of a class type in the same statement that defines the type, if you like. It's equivalent to two separate declarations:

    struct people 
    {
        int id;
    };
    people person;
    

    However, my code I posted above doesn't compile

    It sounds like either your compiler doesn't support C++11 (specifically, assignment from a braced list), or you're compiling with it disabled.

    If you can't use C++11, then you'll have to assign each member separately:

    // person = {3};   // C++11 only
    person.id = 3;
    

    or declare and initialise a local object and assign from that:

    people temp = {3};
    person = temp;
    

    or initialise it in its declaration, rather than deferring until main:

    struct people
    {
        int id;
    } person = {3};
    
    0 讨论(0)
  • 2020-12-22 04:47
    struct people 
    {
        int id;
    } person; // that part
    

    person is the global object of type people.

    person = {3};
    

    Is incorrect in C++03 and correct in C++11, since {3} will be treated like people{3}

    0 讨论(0)
提交回复
热议问题