使用关键字,我做错了什么

using keyword, what i do wrong?

本文关键字:错了 什么 关键字      更新时间:2023-10-16
/* ..CODE.. */
struct st_Settings {
    struct {
        unsigned int x;
        unsigned int y;
        unsigned int width;
        unsigned int height;
    } window;
} defaultSettings;
/* ..CODE.. */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) {
    using st_Settings; // default settings
    {
        using window;
        {
            x = 50;
            y = 50;
            width = 800;
            height = 600;
        }
    }
    /* ..CODE.. */
}

此代码不起作用,这是我的问题,我可以用其他与结构一起使用的东西替换"使用"关键字?


okey我有这样的结构:

struct
{
    struct a
    {
        int a;
        int b;
        int c;
    }
    struct b
    {
        struct a
        {
            int a;
            int b;
            int c;
        }
        struct b
        {
            int a;
            int b;
            int c;
        }
    }
    struct c
    {
        int a;
        int b;
        int c;
    }
} a;

我必须这样做:

a.a.a = 1;
a.a.b = 12;
a.a.c = 14;
a.b.a.a = 41;
a.b.a.b = 61;
a.b.a.c = 34;
a.b.b.a = 65;
a.b.b.b = 45;
a.b.b.c = 23;
a.c.a = 1;
a.c.b = 0;
a.c.c = 4;

,或者可以做这样的事情:

a.
{
    a.
    {
        a = 1;
        b = 12;
        c = 14;
    }
    b.
    {
        a.
        {
            a = 41;
            b = 61;
            c = 34;
        }
        b.
        {
            a = 65;
            b = 45;
            c = 23;
        }
    }
    c.
    {
        a = 1;
        b = 0;
        c = 4;
    }
}

using关键字在您的代码中未正确使用(在代码的这一部分中根本不需要):

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) 
{
    st_Settings settings;
    settings.window.x = 50;
    settings.window.y = 50;
    settings.window.width = 800;
    settings.window.height = 600;
    // ...
}

还请注意,定义结构的方式是定义一个名为defaultSettings的全局实例。如果您想使用它,则将删除上面settings的行声明,并将其所有其他实例替换为defaultSettings

在声明变量时,您想要的唯一的东西是初始化结构:

struct st_Settings {
    struct {
        unsigned int x;
        unsigned int y;
        unsigned int width;
        unsigned int height;
    } window;
} defaultSettings = {{50,50,800,600}};

同时,您可以在功能中初始化:

int a = 10 ;
int b = 20 ;
struct st_Settings declaredAndSetted = {{a,b,defaultSettings.window.width,400}} ;

如果您使用C 0x标准($ g++ -std=c++0x <file>),则可以以这种方式将值重新分配到结构变量:

defaultSettings = {{a,b,defaultSettings.window.width,400}} ;