且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个构造函数,这是默认的?

更新时间:2023-02-14 16:56:14

根据C ++标准


4类X的默认构造函数是类X的构造函数,
可以在没有参数的情况下调用。

4 A default constructor for a class X is a constructor of class X that can be called without an argument.

从您的帖子中不清楚您正在讲什么默认值。

From your post it is not clear what default values you are speaking about. Neither of your declarations is the default constructor.

如果你是在声明中使用默认参数

If you are speaking about default arguments as in the declaration

Person( const string & = "", const string & = "", const string & = "",
const string & = "" );

然后这个声明是一个默认构造函数的声明,因为它可以被调用没有任何明确指定的参数。

Then this declaration is a declaration of the default constructor because it can be called without any explicitly specified argument.

有趣的是,同一个构造函数可以同时是一个默认构造函数和一个非默认构造函数。至少C ++标准不会说任何禁止这个。

It is interesting to note that the same constructor can be a default constructor and a non-default constructor at the same time. At least the C++ Standard does not say anything that forbids this.

例如

struct A
{
   A( int x );
   int x;
};

A a1; // error: there is no default constructor

A::A( int x = 0 ) : x( x ) {}

A a2; // well-formed there is a default constructor.