我有一些像这样的代码:
int a = 5; Foo *foo = new Foo(MoreFoo(a), Bar(a)); // Foo CTOR: Foo(MoreFoo mf, Bar bar): MoreBar(&mf,bar){}我的编译器给了我一个类型的错误:
no matching function for call to ‘Bar::Bar(Bar)’ note: candidates are: note: Bar::Bar(Bar&) no known conversion for argument 1 from ‘Bar’ to ‘Bar&’该错误显然与代码Bar(a) 。 Bar显然有适当的CTOR和CCTOR。 我理解为什么编译器抱怨尝试调用类似Bar::Bar(Bar) ,我正在创建一个无名变量( Bar(a) ),它必须在调用Foo构造函数时被复制,但后来不应该'它只是调用Bar CCTOR? 为什么我收到错误?
编辑:
你为什么要调用Bar::Bar(Bar)而不是Bar::Bar(Bar&) ?
I have some code like this:
int a = 5; Foo *foo = new Foo(MoreFoo(a), Bar(a)); // Foo CTOR: Foo(MoreFoo mf, Bar bar): MoreBar(&mf,bar){}My compiler gives me an error of type:
no matching function for call to ‘Bar::Bar(Bar)’ note: candidates are: note: Bar::Bar(Bar&) no known conversion for argument 1 from ‘Bar’ to ‘Bar&’The error obviously relates to the code Bar(a). Obviously Bar has appropriate CTOR and CCTOR. I understand why the compiler complains about trying to invoke something like Bar::Bar(Bar), I'm creating a nameless variable (Bar(a)) which has to be copied during the call to the Foo constructor, but then shouldn’t it just invoke Bar CCTOR? Why am I getting the error?
Edit:
Why would you ever want to invoke Bar::Bar(Bar) instead of Bar::Bar(Bar&)?
最满意答案
Temporaries不能绑定到引用,除非它们是const -references。
Temporaries cannot be bound to references unless they are references-to-const.
更多推荐
发布评论