在构造函数旁边声明的属性
我对 C/C++ 非常陌生,不确定该方法叫什么。但这就是我来这里试图寻找答案的原因。让我向您展示一个示例,
MyClass::MyClass() : valueOne(1), valueTwo(2)
{
//code
}
其中 valueOne 和 valueTwo 是在主体外部赋值的类属性,这调用了什么方法以及为什么这样做。为什么不这样做
MyClass::MyClass()
{
valueOne = 1;
valueTwo = 2
//code
}
如果有人能帮助我那就太好了。
I am very very new to C/C++ and not sure what the method is called. But thats why I am here trying to find the answer. let me show you an example
MyClass::MyClass() : valueOne(1), valueTwo(2)
{
//code
}
Where valueOne and valueTwo are class properties that are assigned values outside of the body, what method is this called and why is it done this way. Why not do it this way
MyClass::MyClass()
{
valueOne = 1;
valueTwo = 2
//code
}
If anyone can help me out that will be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个初始化列表。您可以在构造函数之后使用初始值设定项列表来初始化成员变量。
默认情况下,构造函数将通过调用其默认构造函数来自动创建作为成员变量的对象。通过使用初始值设定项列表,您可以指定使用其他构造函数。有时,如果您的成员变量没有不带参数的构造函数,则必须使用初始值设定项列表。
That is an initializer list. You can initialize your member variables using an initializer list after the constructor.
By default the constructor will automatically create the objects that are member variables by calling their default constructors. By using an initializer list you can specify to use other constructors. Sometimes if your member variable has no constructor with no argument you have to use an initializer list.
出于效率和性能的原因,初始化列表(前一种样式)通常是首选。就我个人而言,出于代码可读性的原因,我更喜欢它们,因为它将简单的初始化与构造函数本身的任何复杂逻辑分开。
Initialisation lists (the former style) are usually preferred for efficiency and performance reasons. Personally I prefer them for code readability reasons too since it separates simple initialisation from any complex logic in the constructor itself.
这称为初始化列表。这样做主要是为了性能(对于较大的对象)或一致性(对于内置类型,如
int
)。This is called an initialization list. It's done mainly for performance (with larger objects) or consistency (with built-in types like
int
).最好在初始化列表中初始化成员。在你的情况下,这并不重要,但不可能初始化 int&就像您在第二个代码片段中所做的那样。它也是您可以将参数传递给基类构造函数的唯一地方。
It is preferred to initialize members in the initializer list. In your case it doesn't matter, but it is not possible to initialize an int& the way you did in the second code fragment. It is the only place where you can pass arguments to your base class constructor as well.
另请注意,如果仅用于引用 BASE 类中的数据字段或成员函数,则可以在初始值设定项列表中访问 this 指针。
Also note, that the this pointer is accessible in the initializer list if used to reference data fields or member functions in the BASE classes only.