结构构造函数语法 [英] Struct Constructor Syntax
本文介绍了结构构造函数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
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)
{
}
};
推荐答案
构造函数在调用时将 id
初始化为 42
.它被称为初始化列表.
The constructor initializes id
to 42
when it's called. It's called an initliazation list.
在你的例子中,它相当于
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) { }
};
这篇关于结构构造函数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文