c++中的static问题
ringa_lee
ringa_lee 2017-04-17 13:37:38
0
3
862
#include <iostream>

using namespace std;

/*
struct xx
{
    long long _x1;
    char _x2;
    int _x3;
    char _x4[2];
    static int _x5;
};
int xx::_x5 = 0;
*/

int main()
{
    struct xx
    {
        long long _x1;
        char _x2;
        int _x3;
        char _x4[2];
        static int _x5;
    };
    int xx::_x5 = 0;
    cout << sizeof(xx) << endl;

    return 0;
}

请问为什么把那个含有static变量的结构体放在main函数中为什么编译时就会报错啊?
还有就是为什么用sizeof计算出这个结构体所占的大小是24字节啊?我觉得是18字节啊,有人说是需要对整个结构体按照8字节对齐。但是如果只有一个int型的变量在结构体中,比如说:

 struct node
    {
        int x;
    };
    
 这样计算sizeof是4啊,不是按照8字节对齐啊。。请教一下大家
    

ringa_lee
ringa_lee

ringa_lee

reply all(3)
Ty80

The first question: struct/class declared in function is not allowed to have static members (you can imagine the life cycle of this static member).

Second question: The reason for this completion is that two completions occur, which depends on the compiler implementation. You can put the declaration of the second char before the int, connect the two chars together, and then run the program to try. This will only produce one completion.

伊谢尔伦

Answer via mobile phone

I’m not sure about the first question. I haven’t touched C for a long time. I’ll try it on my computer tomorrow. I guess it’s not the problem with the definition, but that int xx::_x5 = 0; cannot be placed in the main function (or you add static in front of the definition) Try it)

The second question is that the structure is aligned to 8 bytes because there is a long long _x1; in the definition that is exactly 8 bytes. The previous picture

was found online. , the situation is not the same as what you said, but it is enough to explain the situation

PHPzhong

For the first question, refer to the question above.
For the second question, please see here: http://www.mycode.net.cn/language/ccplusplus/1489.html

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template