关于C#:没有按预期方式调用复制构造函数

No call to copy constructor as expected

我有一些像这样的代码:

1
2
3
4
5
6
int a = 5;
Foo *foo = new Foo(MoreFoo(a),
    Bar(a));

// Foo CTOR:
Foo(MoreFoo mf, Bar bar): MoreBar(&mf,bar){}

我的编译器给我一个错误类型:

1
2
3
4
no matching function for call to a€?Bar::Bar(Bar)a€?
note: candidates are:
note: Bar::Bar(Bar&)
no known conversion for argument 1 from a€?Bara€? to a€?Bar&a€?

该错误显然与代码Bar(a)有关。显然,Bar具有适当的CTOR和CCTOR。我了解为什么编译器会抱怨尝试调用Bar::Bar(Bar)之类的东西,我正在创建一个无名变量(Bar(a)),该变量必须在调用Foo构造函数的过程中复制,但随后不应该这样做呢?只是调用Bar CCTOR?为什么会出现错误?

编辑:

为什么要调用Bar::Bar(Bar)而不是Bar::Bar(Bar&)


似乎您按照以下方式声明了Bar类的复制构造函数

1
Bar( Bar & );

但是您需要将其声明为

1
Bar( const Bar & );

如果要将临时对象用作参数,因为临时对象可能未绑定到非const引用。


临时文件不能绑定到引用,除非它们是对const的引用。