C++内联类定义和对象初始化
我刚刚遇到以下代码:
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
定义
class
(或struct
)是相当标准的,除了默认是public
而不是private
之外,完全等效)并声明其类型的变量(或指向此类变量的指针等)——这在 C 中是可以的(使用struct
,但正如我已经提到的 C++ 的class
,除了公共与私有之外,与struct
相同)并且C++主要保持与(ISO-1989)C的向上兼容性。从未听说过它有任何特殊名称。It's quite standard to define a
class
(orstruct
, perfectly equivalent except that the default ispublic
instead ofprivate
) and declare a variable of its type (or pointer to such a variable, etc) -- it was OK in C (withstruct
, but as I already mentioned C++'sclass
, save for public vs private, is the same thing asstruct
) and C++ mostly maintains upwards compatibility with (ISO-1989) C. Never heard it called by any special name.