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

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

问题描述

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

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;
}

这个奇怪的例子:bar / code>是什么意思?它似乎初始化成员变量,但我从来没有见过这种语法。它看起来像一个函数/构造函数调用,但 int ?对我来说没有意义。也许有人可以启迪我。

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 a ordinary C++ book?

推荐答案

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

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).

常见问题条目的要点是


如果使用初始化列表而不是赋值,代码将运行得更快。

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

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

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