在C ++中是否有一个隐式默认构造函数? [英] Is there an implicit default constructor in C++?

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

问题描述

在我正在阅读的书中( C ++ Without Fear ),它说如果你不会声明一个类的默认构造函数,编译器为您提供一个,它将每个数据成员置零。我已经尝试了这个,我没有看到任何归零行为。我也找不到任何在Google上提及此内容的内容。

In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?

推荐答案

如果你没有定义一个构造函数,编译器会定义一个一个默认的构造函数为你。

If you do not define a constructor, the compiler will define a default constructor for you.


  • 默认构造基类(如果基类没有默认构造函数,这是编译失败)

  • 默认构造每个成员变量声明的顺序。 (如果成员没有默认构造函数,则这是一个编译失败)。

注意:

POD数据(int,float,pointer等)没有一个显式的构造函数,但默认动作是不做任何事(在C ++哲学的叶片;我们不想支付的东西,除非我们明确要求它)

Note:
The POD data (int,float,pointer, etc.) do not have an explicit constructor but the default action is to do nothing (in the vane of C++ philosophy; we do not want to pay for something unless we explicitly ask for it).

如果没有定义析构函数/复制构造函数/赋值运算符,编译器将为您构建一个(因此类总是有一个析构函数/复制构造函数/赋值运算符除非你欺骗和明确声明一个但不定义它)。)

默认实现是:

If no destructor/copy Constructor/Assignment operator is defined the compiler builds one of those for you (so a class always has a destructor/Copy Constructor/Assignment Operator (unless you cheat and explicitly declare one but don't define it)).
The default implementation is:


  • 如果定义了用户定义的析构函数,请执行所提供的代码。

  • 以相反的顺序调用每个成员的析构函数


  • 调用Base类的复制构造函数。

  • 按声明顺序调用每个成员变量的复制构造函数。


  • 基本类赋值运算符

  • 按声明顺序调用每个成员变量的赋值运算符。

  • 返回对此的引用。

注意POD数据的复制构造/分配操作符只是复制数据(因此,与RAW指针相关联的浅复制问题)。

Note Copy Construction/Assignment operator of POD Data is just copying the data (Hence the shallow copy problem associated with RAW pointers).

这篇关于在C ++中是否有一个隐式默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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