C++ 结构构造函数语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9145822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Struct Constructor Syntax
提问by Cemre
Possible Duplicate:
What does a colon following a C++ constructor name do?
可能的重复:
C++ 构造函数名称后面的冒号有什么作用?
I found the example below online however the syntax for the constructor confuses me a little bit especially the : symbol. Could anyone please give me a brief explanation ? Thanks.
我在网上找到了下面的例子,但是构造函数的语法让我有点困惑,尤其是 : 符号。谁能给我一个简短的解释?谢谢。
struct TestStruct {
int id;
TestStruct() : id(42)
{
}
};
回答by dee-see
The constructor initializes id
to 42
when it's called. It's called an initliazation list.
构造函数初始化id
为42
调用时。它被称为初始化列表。
In your example, it is equivalent to
在你的例子中,它相当于
struct TestStruct {
int id;
TestStruct()
{
id = 42;
}
};
You can do it with several members as well
你也可以和几个成员一起做
struct TestStruct {
int id;
double number;
TestStruct() : id(42), number(4.1)
{
}
};
It's useful when your constructor's only purpose is initializing member variables
当构造函数的唯一目的是初始化成员变量时,它很有用
struct TestStruct {
int id;
double number;
TestStruct(int anInt, double aDouble) : id(anInt), number(aDouble) { }
};
回答by SGosal
It's a constructor initialization list. You can learn more about it here:
这是一个构造函数初始化列表。您可以在此处了解更多信息:
http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/
http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/