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

时间:2014-01-27 14:33:15

标签: c++ using

/* ..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;
    }
}

2 个答案:

答案 0 :(得分:0)

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替换它的所有其他实例。

答案 1 :(得分:0)

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

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 standard($ g++ -std=c++0x <file>),可以用这种方式将值重新分配给结构变量:

defaultSettings = {{a,b,defaultSettings.window.width,400}} ;
相关问题