默认构造函数与隐式构造函数 [英] Defaulted constructor vs implicit constructor

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

问题描述

可能有人已经对此进行了询问,但是搜索默认,默认,显式等并不能取得很好的效果。

It's possible that someone has already asked about this but googling for "default", "defaulted", "explicit" and so on doesn't give good results. But anyway.

我已经知道显式定义的默认构造函数(即不带参数)和显式定义的默认构造函数(即关键字<$ c)之间存在一些差异$ c>默认),从此处:新关键字= C ++ 11中的默认值

I already know there are some differences between an explicitly defined default construtor (i.e. without arguments) and an explicitly defined defaulted constructor (i.e. with the keyword default), from here: The new keyword =default in C++11

但是显式定义的默认构造函数和隐式定义的构造函数之间有什么区别(即,当用户不编写它时)

But what are the differences between an explicitly defined defaulted constructor and implicitly defined one (i.e. when the user doesn't write it at all)?

class A
{
public:
    A() = default;
    // other stuff
};

vs

class A
{
    // other stuff
};

我想到的一件事是,当存在非默认构造函数时,用户还拥有明确定义默认构造函数。但是还有其他区别吗?

One thing that comes to mind is that when there is a non-default constructor then the user also has to define a default constructor explicitly. But are there any other differences?

编辑:我主要是想知道是否有充分的理由写 A()= default; 而不是完全省略构造函数(当然,假设它是该类的唯一显式定义的构造函数)。

I'm mostly interested in knowing if there's any good reason to write A() = default; instead of just omitting the constructor altogether (assuming it's the only explicitly defined constructor for the class, of course).

推荐答案

= default 的目的是使隐式定义明确。隐式定义版本和显式默认版本之间的任何差异都限于由于存在显式声明而出现的其他一些可能性。

The purpose of = default is to make the implicit definition explicit. Any differences between an implicitly defined version and the explicitly defaulted version are limited to some additional possibilities appearing due to the presence of an explicit declaration.


  1. 隐式声明/定义的构造函数始终为 public ,而显式定义的默认构造函数的访问控制在您自己的控制之下。

  1. The implicitly declared/defined constructor is always public, whereas the access control of the explicitly defined defaulted constructor is under your own control.

定义默认的默认构造函数使您可以使用属性对其进行注释。例如:

Defining a defaulted default constructor enables you annotating it with attributes. For example:

$ cat a.cpp 
class A
{
public:
    [[deprecated]] A() = default;
};

int main()
{
    A a;
}

$ g++ -std=c++14 a.cpp
a.cpp: In function ‘int main()’:
a.cpp:9:7: warning: ‘constexpr A::A()’ is deprecated [-Wdeprecated-declarations]
     A a;
       ^
a.cpp:4:20: note: declared here
     [[deprecated]] A() = default;
                    ^


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

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