在没有引用的情况下复制构造函数的签名
Copy constructor's signature without reference
如果我有一个点 class,复制构造函数应该是这样的:
Point(const Point &p);
Point(Point &p);
但是,如果我想创建一个需要点的构造函数怎么办?为什么它被认为是复制构造函数,而不是构造函数?
Point(const Point p)
编译器错误:"copy constructor for class "Point" 可能没有 "Point"
类型的参数
您不能使用复制构造函数签名来按值接受参数。原因很简单-为了按值传递参数,您需要调用复制构造函数,这将需要按值传递参数,并将调用复制构造函数...欢迎使用无休止的递归。
编译器不允许这种构造,为您省去了很多麻烦。
Point(const Point p)
Why is it considered as copy constructor, instead of a constructor?
不是。
正如标准在 §12.8/2 中所说:
A non-template constructor for class X
is a copy constructor if its
first parameter is of type X&
, const X&
, volatile X&
or const volatile X&
, and either there are no other parameters or else all other
parameters have default arguments (...).
其实你的声明是ill-formed。 §12.8/6 说:
A declaration of a constructor for a class X
is ill-formed if its
first parameter is of type (optionally cv-qualified) X
and either
there are no other parameters or else all other parameters have
default arguments.
您确实拥有:class Point
的构造函数,其第一个参数是 const Point
类型并且没有其他参数。
这当然是正式的解释。正如其他人所解释的那样,这种构造函数的实际含义是无限递归。
也许您担心收到的错误消息。但是,对于编译器生成的诊断消息 的内容绝对没有规则。这是一个 quality-of-implementation 问题;如果您的编译器认为 class "Point" 的 复制构造函数可能没有 "Point" 类型的参数是将问题传达给它的好方法用户,那就这样吧。
如果我有一个点 class,复制构造函数应该是这样的:
Point(const Point &p);
Point(Point &p);
但是,如果我想创建一个需要点的构造函数怎么办?为什么它被认为是复制构造函数,而不是构造函数?
Point(const Point p)
编译器错误:"copy constructor for class "Point" 可能没有 "Point"
类型的参数您不能使用复制构造函数签名来按值接受参数。原因很简单-为了按值传递参数,您需要调用复制构造函数,这将需要按值传递参数,并将调用复制构造函数...欢迎使用无休止的递归。
编译器不允许这种构造,为您省去了很多麻烦。
Point(const Point p)
Why is it considered as copy constructor, instead of a constructor?
不是。
正如标准在 §12.8/2 中所说:
A non-template constructor for class
X
is a copy constructor if its first parameter is of typeX&
,const X&
,volatile X&
orconst volatile X&
, and either there are no other parameters or else all other parameters have default arguments (...).
其实你的声明是ill-formed。 §12.8/6 说:
A declaration of a constructor for a class
X
is ill-formed if its first parameter is of type (optionally cv-qualified)X
and either there are no other parameters or else all other parameters have default arguments.
您确实拥有:class Point
的构造函数,其第一个参数是 const Point
类型并且没有其他参数。
这当然是正式的解释。正如其他人所解释的那样,这种构造函数的实际含义是无限递归。
也许您担心收到的错误消息。但是,对于编译器生成的诊断消息 的内容绝对没有规则。这是一个 quality-of-implementation 问题;如果您的编译器认为 class "Point" 的 复制构造函数可能没有 "Point" 类型的参数是将问题传达给它的好方法用户,那就这样吧。