来自 c++ 的奇怪代码段
阅读其他帖子中的代码,我看到类似的内容。
struct Foo {
Foo() : mem(0) {}
int mem;
};
在这种情况下,mem(0) {} 会做什么,特别是对于大括号?我以前从未见过这个,也不知道我还能在哪里找到这个。我知道 mem(0) 会将 mem 初始化为 0,但为什么要使用 {}?
谢谢。
Reading code from other posts, I'm seeing something like this.
struct Foo {
Foo() : mem(0) {}
int mem;
};
What does mem(0) {} does in this case, especially regarding the curly brackets? I have never seen this before and have no idea where else I would find out about this. I know that mem(0), would intialize mem to 0, but why the {}?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于
Foo()
是类的构造函数,因此它必须有一个主体,即使成员变量mem
是在其外部初始化的。这就是为什么在您的示例中,构造函数的主体为空:
Since
Foo()
is the class' constructor, it must have a body, even if the member variablemem
is initialized outside of it.That's why, in your example, the constructor has an empty body:
它定义了类的构造函数。冒号后面的部分是初始化列表,其中使用构造函数调用将
mem
成员初始化为零。比较:
这两者的作用相同,但前者更符合 C++ 中对象构造的典型外观。
It defines the constructor of the class. The part after the colon is the initialization list, in which the
mem
member is initialized to zero using a constructor call.Compare:
These two do the same, but the former is more in line with how object construction typically looks in C++.
int c++ 你可以在.h文件中定义你的方法实现
通常它在模板实现中使用。另外,如果您想避免库链接,并且您更愿意向用户提供所有代码,以便他可以包含您的文件,而无需将任何 lib 文件链接到他的项目,您也可以使用这种类声明方法。
int c++ you can define your method implementation in .h file
Usually it used in templates implementation. Also you could use this method of class declaration in case you would like to avoid libraries linking and you prefer to give to user all your code so he can include your file without linking any lib file to his project.