你好,我有下面这样的代码,我不知道它为什么不起作用。
class Clazz2;
class Clazz
{
public:
void smth(Clazz2& c)
{
}
void smth2(const Clazz2& c)
{
}
};
class Clazz2
{
int a,b;
};
int main()
{
Clazz a;
Clazz2 z;
a.smth(z);
//a.smth(Clazz2()); //<-- this doesn't work
a.smth2(Clazz2()); // <-- this is ok
return 0;
}
我有编译错误:
g++ -Wall -c "test.cpp" (in directory: /home/asdf/Desktop/tmp)
test.cpp: In function ‘int main()’:
test.cpp:26:17: error: no matching function for call to ‘Clazz::smth(Clazz2)’
test.cpp:26:17: note: candidate is:
test.cpp:5:7: note: void Clazz::smth(Clazz2&)
test.cpp:5:7: note: no known conversion for argument 1 from ‘Clazz2’ to ‘Clazz2&’
Compilation failed.
答案 0 :(得分:6)
这是因为不允许非常量引用绑定到临时对象。另一方面,对const
的引用可以绑定到临时对象(参见C ++ 11标准的8.3.5 / 5)。
答案 1 :(得分:2)
您的第一个smth2
接受一个引用,该引用不能像构造函数a.smth(Claszz2())
那样绑定到临时值。但是, const 引用可以绑定到临时引用,因为我们无法修改临时引用,因此允许它。
在C ++ 11中,您可以使用 rvalue-refrerence ,这样您就可以绑定临时对象了:
void smth2(Clazz2 &&);
int main()
{
a.smth(Claszz2()); // calls the rvalue overload
}