构造函数中这个奇怪的冒号成员(“:")语法是什么? [英] What is this weird colon-member (" : ") syntax in the constructor?

查看:38
本文介绍了构造函数中这个奇怪的冒号成员(“:")语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我看到了一个像下面这样的例子:

#include 类 Foo {民众:国际酒吧;Foo(int num): bar(num) {};};int main(void) {std::cout <<Foo(42).bar <<std::endl;返回0;}

这个奇怪的 : bar(num) 是什么意思?它似乎以某种方式初始化了成员变量,但我以前从未见过这种语法.它看起来像一个函数/构造函数调用,但对于 int?对我来说毫无意义.也许有人可以启发我.顺便说一句,还有其他像这样的深奥的语言特性,你在普通的 C++ 书中永远找不到吗?

解决方案

这是一个成员初始化列表.您应该在任何优秀的 C++ 书籍中找到有关它的信息.>

在大多数情况下,您应该初始化成员初始化列表中的所有成员对象(但是,请注意 FAQ 条目末尾列出的例外情况).

FAQ 条目的要点是,

<块引用>

在所有其他条件相同的情况下,如果您使用初始化列表而不是赋值,您的代码将运行得更快.

Recently I've seen an example like the following:

#include <iostream>

class Foo {
public:
  int bar;
  Foo(int num): bar(num) {};
};

int main(void) {
  std::cout << Foo(42).bar << std::endl;
  return 0;
}

What does this strange : bar(num) mean? It somehow seems to initialize the member variable but I've never seen this syntax before. It looks like a function/constructor call but for an int? Makes no sense for me. Perhaps someone could enlighten me. And, by the way, are there any other esoteric language features like this, you'll never find in an ordinary C++ book?

解决方案

It's a member initialization list. You should find information about it in any good C++ book.

You should, in most cases, initialize all member objects in the member initialization list (however, do note the exceptions listed at the end of the FAQ entry).

The takeaway point from the FAQ entry is that,

All other things being equal, your code will run faster if you use initialization lists rather than assignment.

这篇关于构造函数中这个奇怪的冒号成员(“:")语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆