关于c ++转换:参数1从'[some_class]'到'[some_class]&'的未知转换 [英] about c++ conversion : no known conversion for argument 1 from ‘[some_class]' to ‘[some_class]&’
问题描述
我正在使用C ++,但出现了一个我不知道确切原因的错误.我已经找到了解决方案,但仍然想知道为什么.
I'm working on C++, and had an error that I didn't know the exact reason. I've found the solution, but still want to know why.
class Base
{
public:
void something(Base& b){}
};
int main()
{
Base b;
b.something(Base());
return 0;
}
编译代码时,出现以下错误:
when I compile the code, I got this following error :
abc.cpp:12:20: error: no matching function for call to ‘Base::something(Base)’
abc.cpp:12:20: note: candidate is:
abc.cpp:6:7: note: void Base::something(Base&)
abc.cpp:6:7: note: no known conversion for argument 1 from ‘Base’ to ‘Base&’
但是当我将b.something(Base())替换为
but when I replaced b.something(Base()) into
Base c;
b.something(c);
错误消失了,我想知道为什么吗???他们不是同一类型吗?只是我写的方式很重要,但含义应该是相同的??
the error is gone, I'm wondering why??? aren't they have the same type? It only matters how I write it, but the meaning should be the same???
谢谢你们!
推荐答案
您要在此处传递一个临时 Base
对象:
You are passing a temporary Base
object here:
b.something(Base());
但是您尝试在此处将其绑定到非常量左值引用:
but you try to bind that to a non-const lvalue reference here:
void something(Base& b){}
这在标准C ++中是不允许的.您需要一个 const
参考.
This is not allowed in standard C++. You need a const
reference.
void something(const Base& b){}
执行此操作时:
Base c;
b.something(c);
您没有通过临时工.非常量引用绑定到 c
.
you are not passing a temporary. The non-const reference binds to c
.
这篇关于关于c ++转换:参数1从'[some_class]'到'[some_class]&'的未知转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!