构造函数:这句话是什么意思? [英] Constructors : What does this statement mean?

查看:94
本文介绍了构造函数:这句话是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class myclass
{
  int my1,my2;
  public:
  myclass(int num1,int num2) : my1(num1),my2(num2)
  {

  }

};



构造函数中的语句:my1(num1),my2(num2)是什么意思?
您能帮我了解这是做什么的吗?

非常感谢!



What does the statement in the constructor : my1(num1),my2(num2) mean?
Can you please help me understand what does this do?

Thank you very much!

推荐答案

这意味着将变量my1的值设置为输入参数num1,将my2的值设置为输入参数num2.此信息可在 MSDN参考中免费获得 [
It means set the value of variable my1 to the input parameter num1, and the value of my2 to the input parameter num2. This information is freely available in the MSDN reference[^].
It''s just an alternative way of writing:
myclass(int num1,int num2)
{
    my1 = num1;
    my2 = num2;
}


这是一种可以从构造函数内部初始化成员变量的方法.确实与以这种方式编写构造函数没什么不同.
It is one way in which member variables can be initialized from within the constructor. It is really no different than writing the constructor this way.
myclass(int num1, int num2)
{
   my1 = num1;
   my2 = num2;
}


构造函数参数列表之后的":"之后的列表称为初始化器列表或初始化列表.它是一个用逗号分隔的初始化程序"列表,其中每个项目都定义了该类的成员变量或该类的基类的初始化.对于成员变量,变量名后跟一个参数(在方括号中),该参数用于通过复制构造来构造变量.如果是基类,则可以传递一个可变长度的参数列表(同样,用括号括起来),该列表与该基类的任何构造函数定义相对应.

此外,初始化的顺序可能取决于您在初始化列表中的内容(但我认为这不会影响成员变量).我无法确定我曾经下载的有关该文章的内容,但IIRC的构建顺序为:
1.虚拟基类
2.基类(从最接近的级别开始)
3.成员变量

我不确定1.和2.但是我很确定初始化列表中的成员变量总是最后初始化,即i. e.您可以使用基类中的数据和函数来初始化初始化列表中的成员变量.

就是说,最好不要做任何与初始化顺序有关的事情,以免使您的同事感到困惑;)
The list following the '':'' after the constructor parameter list is called initializer list or initialization list. It is a comma-separated list of ''initializers'', where each item defines the intialization of either a member variable of the class, or a base class of the class. In case of a member variable, the name of the variable is followed by a single argument (in brackets) that is used to construct the variable via copy-construction. In case of a base class, a variable length argument list (again, in brackets) may be passed that corresponds to any constructor definition of that base class.

Also, the order of initialization may depend on what you put in the initializer list (but I think this does not affect member variables). I can''t pinpoint the article I once downloaded about that, but IIRC the order of construction is:
1. virtual base classes
2. base classes (closest level first)
3. member variables

I''m not sure about 1. and 2. but I''m quite sure member variables in initializer lists are always initialized last, i. e. you can use data and functions from your base classes for the purpose of initializing your member variables in the initialization list.

That said, it''s probably better not to do anything that depends on the order of initialization, if only to not confuse your colleagues ;)


这篇关于构造函数:这句话是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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