没有按预期调用复制构造函数(No call to copy constructor as expected)

编程入门 行业动态 更新时间:2024-10-26 01:23:14
没有按预期调用复制构造函数(No call to copy constructor as expected)

我有一些像这样的代码:

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.

更多推荐

本文发布于:2023-07-29 18:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1318667.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   call   copy   constructor   expected

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!