关于 C++ 转换:参数 1 从 '[some_class]' 到 '[some_class]&' 没有已知的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20247525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
about c++ conversion : no known conversion for argument 1 from ‘[some_class]' to ‘[some_class]&’
提问by user430926
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.
我正在研究 C++,但遇到了一个我不知道确切原因的错误。我已经找到了解决方案,但仍然想知道原因。
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&'
but when I replaced b.something(Base()) into
但是当我将 b.something(Base()) 替换为
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???
错误消失了,我想知道为什么???他们不是有相同的类型吗?重要的是我怎么写,但意思应该是一样的???
Thanks Guys!
谢谢你们!
采纳答案by juanchopanza
You are passing a temporary Base
object here:
你在Base
这里传递一个临时对象:
b.something(Base());
but you try to bind that to a non-const lvalue reference here:
但是您尝试将其绑定到非常量左值引用:
void something(Base& b){}
This is not allowed in standard C++. You need a const
reference.
这在标准 C++ 中是不允许的。你需要一个const
参考。
void something(const Base& b){}
When you do this:
当你这样做时:
Base c;
b.something(c);
you are not passing a temporary. The non-const reference binds to c
.
你不是通过一个临时的。非常量引用绑定到c
.
回答by Ivaylo Strandjev
In the first case you attempt to pass a (non-const)reference to a temporary as argument to a function which is not possible. In the second case you pass a reference to an existing object which is perfectly valid.
在第一种情况下,您尝试将一个(非常量)临时引用作为参数传递给一个函数,这是不可能的。在第二种情况下,您传递对完全有效的现有对象的引用。