C++内联类定义和对象初始化

发布于 2024-08-23 12:07:34 字数 470 浏览 3 评论 0原文

我刚刚遇到以下代码:

#include <iostream>

static class Foo
{
public:
    Foo()
    {
        std::cout << "HELLO" << std::endl;
    }

    void foo()
    {
        std::cout << "in foo" << std::endl;
    }

}
    blah;

int main()
{
    std::cout << "exiting" << std::endl;
    blah.foo();
    return 0;
}

我之前没有见过上面定义变量的方法 - 类定义是与变量定义内联完成的。这让我想起了Java中的匿名类。这叫什么?它在 C++ 标准中吗?

谢谢塔拉斯

I've just come across the following code:

#include <iostream>

static class Foo
{
public:
    Foo()
    {
        std::cout << "HELLO" << std::endl;
    }

    void foo()
    {
        std::cout << "in foo" << std::endl;
    }

}
    blah;

int main()
{
    std::cout << "exiting" << std::endl;
    blah.foo();
    return 0;
}

I haven't seen the above method of definining a variable before - the class definition is done inline with the variable definition. It reminds me of anonymous classes in Java. What is this called, and is it in the C++ standard?

Thanks

Taras

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

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

发布评论

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

评论(1

别在捏我脸啦 2024-08-30 12:07:34

定义class(或struct)是相当标准的,除了默认是public而不是private之外,完全等效)并声明其类型的变量(或指向此类变量的指针等)——这在 C 中是可以的(使用 struct,但正如我已经提到的 C++ 的 class ,除了公共与私有之外,与struct相同)并且C++主要保持与(ISO-1989)C的向上兼容性。从未听说过它有任何特殊名称。

It's quite standard to define a class (or struct, perfectly equivalent except that the default is public instead of private) and declare a variable of its type (or pointer to such a variable, etc) -- it was OK in C (with struct, but as I already mentioned C++'s class, save for public vs private, is the same thing as struct) and C++ mostly maintains upwards compatibility with (ISO-1989) C. Never heard it called by any special name.

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