Foo f = Foo(); //没有匹配函数调用'Foo :: Foo(Foo)'... huh? [英] Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)' ... huh?
问题描述
class Foo
{
public:
explicit Foo(){}
explicit Foo(Foo&){}
};
Foo d = Foo();
错误:没有匹配函数调用'Foo: :Foo(Foo)'
我尝试更改 Foo C $ c>到
Foo(Foo)
,因为AFAIK不是一个有效的构造函数,并且我得到:
错误:无效的构造函数;你可能意味着Foo(const Foo&)
如何解决这个问题? (这是GCC上的)
在你的复制构造函数中有两个有问题的东西。
首先,你使复制构造函数显式(这是一个值得怀疑的事情),所以你(理论上)需要做:
Foo d((Foo()));
其次,你的拷贝构造函数接受一个引用,而不是 const
参考,这意味着您不能将其与临时 Foo
一起使用。
'd只要从复制构造函数中删除 explicit
,并尽可能使用 const
请注意,默认构造函数中的 explicit
没有效果。[*] explicit
只对可以使用单个参数调用的构造函数有影响。它阻止它们用于隐式转换。对于只有零个或只有两个或多个参数的构造函数,它没有效果。
[注意:
Foo d;
和
Foo d = Foo();
但在这种情况下你有一个用户声明的默认构造函数,所以这不适用。 / p>
编辑:
[*]我刚刚复选了这个和12.3.1 [class.conv.ctor]你可以使一个默认构造函数 explicit
。在这种情况下,构造函数将用于执行默认初始化或值初始化。说实话,我不明白这个的价值,如果你有一个用户声明的构造函数,那么它是一个非POD类型,甚至非POD类型的本地对象是默认初始化的,如果他们没有初始化该子句说明可以通过显式
默认构造函数来完成。也许有人可以指出一个角落的情况下,它确实有所作为,但现在我看不出什么效果显式
对默认构造函数。
class Foo
{
public:
explicit Foo() {}
explicit Foo(Foo&) {}
};
Foo d = Foo();
error: no matching function for call to 'Foo::Foo(Foo)'
I tried changing Foo(Foo&)
to Foo(Foo)
as the error suggests, which AFAIK is not a valid constructor, and sure enough I get:
error: invalid constructor; you probably meant ‘Foo (const Foo&)’
What gives? How do I resolve this? (This is on GCC by the way)
There are two questionable things that you have in your copy constructor.
First, you've made the copy-constructor explicit (which is a questionable thing to do), so you would (in theory) need to do:
Foo d( (Foo()) );
Second, your copy constructor takes a reference and not a const
reference which means that you can't use it with a temporary Foo
.
Personally, I'd just remove explicit
from the copy-constructor and make it take a const
reference if possible.
Note that the explicit
on your default constructor has no effect.[*] explicit
only has an effect on constructors that can be called with a single parameter. It prevents them being used for implicit conversions. For constructors that take only zero or only two or more parameters, it has no effect.
[Note: there can be a difference between:
Foo d;
and
Foo d = Foo();
but in this case you have a user-declared default constructor so this doesn't apply.]
Edit:
[*] I've just double checked this and 12.3.1 [class.conv.ctor] says that you can make a default constructor explicit
. In this case the constructor will be used to perform default-initialization or value-initialization. To be honest, I don't understand the value of this as if you have a user-declared constructor then it's a non-POD type and even local objects of non-POD type are default-initialized if they don't have an initializer which this clause says can be done by an explicit
default constructor. Perhaps someone can point out a corner case where it does make a difference but for now I don't see what effect explicit
has on a default constructor.
这篇关于Foo f = Foo(); //没有匹配函数调用'Foo :: Foo(Foo)'... huh?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!