构造器初始化Vs赋值 [英] Constructor initialization Vs assignment

查看:92
本文介绍了构造器初始化Vs赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑下列类:

class test1
{
    private:
        int a;
        int b;
    public:
        test1():a(0),b(0){}
};

class test2
{
    private:
        int a;
        int b;
    public:
        test2()
        {
            a=0;
            b=0;
        }
};

现在,我知道 test1()构造函数是初始化的数据成员的正确方法,因为在 test2()不初始化。我的问题是:

Now, I know that test1() constructor is the right way to initialize the data members of a class, because in test2() we are performing assignment and not initialization. My questions are:


  1. 如果我们执行作业而不是初始化,可能会出错?

  2. test1()构造函数的情况下,编译器内部执行赋值操作?如果没有,那么这些是如何初始化的?

  1. What might go wrong if we perform assignment instead of initialization?
  2. Doesn't the compiler internally perform assignment in case of test1() constructor? If no then how are these initialized?


推荐答案


What might go wrong if we perform assignment instead of initialization?

一些类类型(以及引用和 const objects)无法分配;一些不能默认初始化;一些可能比默认初始化和重新赋值比直接初始化更昂贵。

Some class types (and also references and const objects) can't be assigned; some can't be default-initialised; some might be more expensive to default-initialise and reassign than to initialise directly.


编译器在内部不执行赋值()构造函数?如果没有,那么这些是如何初始化的?

Doesn't the compiler internally performs assignment in case of test1() constructor? If no then how are these initialized?

int ,两者之间几乎没有或没有实际差异。默认初始化不做任何事情,直接初始化和赋值都基本上是一样的。

In the case of primitive types like int, there is little or no practical difference between the two. Default-initialisation does nothing, and direct-initialisation and assignment both do essentially the same thing.

在类类型的情况下,默认初始化,赋值和直接初始化每个调用不同的用户定义函数,并且一些操作可能根本不存在;所以一般来说,两个例子可能有非常不同的行为。

In the case of class types, default-initialisation, assignment and direct-initialisation each call different user-defined functions, and some operations may not exist at all; so in general the two examples could have very different behaviour.

这篇关于构造器初始化Vs赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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