C ++构造函数定义 [英] C++ Constructor definition

查看:177
本文介绍了C ++构造函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class myClass
{
    int var1,var2;
    public:
       myClass(int a1, int b1) : var1(a1), var2(b1)
       {
       }
};



这是有效的构造函数定义吗?

谢谢!



is this a valid constructor definition?

Thanks!

推荐答案

是的,这是有效的C ++,并且可以编译-我对其进行了测试.构造函数允许在创建myClass类的对象时设置var1和var2.
Yes this is valid C++ and it compiles - I tested it. The constructor allows setting var1 and var2 when creating an object of the myClass class.


hi,
是的,它是有效的Ctor.这称为初始化列表,此处两个变量都已初始化为"var1(a1),var2(b1)".它比在Ctor中分配值(如下所示)更优化和更快.


Yes it is a valid Ctor. This is called the initialization list, here both the variables are getting initialized "var1(a1), var2(b1)". Its more optimized and faster than assigning the values in Ctor as given below.

class myClass
{
    int var1,var2;
    public:
       myClass(int a1, int b1) 
       {
          var1 =a1; 
          var2 =b1;
       }
};



这也是在c ++中为常量类变量赋值的唯一方法.因为常量变量在定义它时必须用值初始化(并且不能赋值),并且C ++不允许在类定义内初始化vars.



Also this is the only way to assign values to the constant class variables in c++. As the constant variables has to be initialized with the value (and must not be assigned) while defining it and C++ don''t allow to initialize vars inside class definition.


是的,并且与此问题 [
Yes, and it is exactly the same as this question[^] that you asked yesterday. Instead of posting your exam questions here, why not re-read your course notes.


这篇关于C ++构造函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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