如何使用匿名结构或类?

发布于 2024-12-17 02:32:27 字数 438 浏览 3 评论 0原文

因此,可以声明匿名类或结构,但如何使其有用?

int main() {
    class{
        int ClassVal;
    };
    struct{
        short StructVal;
    };
    StructVal = 5;   //StructVal is undefined
    ClassVal = 5;    //ClassVal is undefined too?
    return 0;
}

如果您将它们都放在主函数之外,它们也将无法访问。 我问这个只是因为它有点有趣:)

编辑: 为什么主函数外部(全局范围)的 union 必须静态声明 例如:

static struct {
    int x;
};
int main() {
   //...
}

So, it's possible to declalre anonymous class or struct but how to I make it useful?

int main() {
    class{
        int ClassVal;
    };
    struct{
        short StructVal;
    };
    StructVal = 5;   //StructVal is undefined
    ClassVal = 5;    //ClassVal is undefined too?
    return 0;
}

if you put both of them outside of main function they will be inaccessible as well.
I'm asking this only because it's somehow intersting :)

EDIT:
Why union outside of main function (at global scope) must be static declared
for example:

static struct {
    int x;
};
int main() {
   //...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巴黎夜雨 2024-12-24 02:32:27

匿名类和结构可用于直接定义变量:

int main()
{
    class
    {
        int ClassVal;
    } classVar;

    struct
    {
        short StructVal;
    } structVar;

    structVar.StructVal = 5;
    classVar.ClassVal = 5;

    return 0;
}

上面的情况并不常见,但在西蒙·里克特(Simon Richter)在他的回答中描述的联合中使用时非常常见。

Anonymous classes and structures may be used to directly define a variable:

int main()
{
    class
    {
        int ClassVal;
    } classVar;

    struct
    {
        short StructVal;
    } structVar;

    structVar.StructVal = 5;
    classVar.ClassVal = 5;

    return 0;
}

The above is not very common like that, but very common when used in unions as described by Simon Richter in his answer.

揽月 2024-12-24 02:32:27

这些在嵌套structunion的形式中最有用:

struct typed_data {
    enum type t;
    union {
        int i;                       // simple value
        struct {
            union {                  // any of these need a length as well
                char *cp;
                unsigned char *ucp;
                wchar_t *wcp;
            };
            unsigned int len;
        };
    };
 };

现在typed_data被声明为具有成员t的类型code>、icpucpwcplen,最小化其预期用途的存储要求。

These are most useful in the form of nested struct and union:

struct typed_data {
    enum type t;
    union {
        int i;                       // simple value
        struct {
            union {                  // any of these need a length as well
                char *cp;
                unsigned char *ucp;
                wchar_t *wcp;
            };
            unsigned int len;
        };
    };
 };

Now typed_data is declared as a type with the members t, i, cp, ucp, wcp and len, with minimal storage requirements for its intended use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文